code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class MainHandler(webapp.RequestHandler): def get(self): self.response.out.write(""" <html> <body> <center> <h1>Hello world!</h1> </center> </body> </html> """) def main(): application = webapp.WSGIApplication( [ ('/', MainHandler) ], debug=True) run_wsgi_app(application) if __name__ == '__main__': main()
Python
#!/usr/bin/python2.4 # # Copyright 2007 The Python-Twitter Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl except: from cgi import parse_qsl import oauth2 as oauth REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' consumer_key = None consumer_secret = None if consumer_key is None or consumer_secret is None: print 'You need to edit this script and provide values for the' print 'consumer_key and also consumer_secret.' print '' print 'The values you need come from Twitter - you need to register' print 'as a developer your "application". This is needed only until' print 'Twitter finishes the idea they have of a way to allow open-source' print 'based libraries to have a token that can be used to generate a' print 'one-time use key that will allow the library to make the request' print 'on your behalf.' print '' sys.exit(1) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) oauth_client = oauth.Client(oauth_consumer) print 'Requesting temp token from Twitter' resp, content = oauth_client.request(REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': print 'Invalid respond from Twitter requesting temp token: %s' % resp['status'] else: request_token = dict(parse_qsl(content)) print '' print 'Please visit this Twitter page and retrieve the pincode to be used' print 'in the next step to obtaining an Authentication Token:' print '' print '%s?oauth_token=%s' % (AUTHORIZATION_URL, request_token['oauth_token']) print '' pincode = raw_input('Pincode? ') token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(pincode) print '' print 'Generating and signing request for an access token' print '' oauth_client = oauth.Client(oauth_consumer, token) resp, content = oauth_client.request(ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % pincode) access_token = dict(parse_qsl(content)) if resp['status'] != '200': print 'The request for a Token did not succeed: %s' % resp['status'] print access_token else: print 'Your Twitter Access Token key: %s' % access_token['oauth_token'] print ' Access Token secret: %s' % access_token['oauth_token_secret'] print ''
Python
#!/usr/bin/python2.4 # -*- coding: utf-8 -*-# # # Copyright 2007 The Python-Twitter Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''Unit tests for the twitter.py library''' __author__ = 'python-twitter@googlegroups.com' import os import simplejson import time import calendar import unittest import urllib import twitter class StatusTest(unittest.TestCase): SAMPLE_JSON = '''{"created_at": "Fri Jan 26 23:17:14 +0000 2007", "id": 4391023, "text": "A l\u00e9gp\u00e1rn\u00e1s haj\u00f3m tele van angoln\u00e1kkal.", "user": {"description": "Canvas. JC Penny. Three ninety-eight.", "id": 718443, "location": "Okinawa, Japan", "name": "Kesuke Miyagi", "profile_image_url": "https://twitter.com/system/user/profile_image/718443/normal/kesuke.png", "screen_name": "kesuke", "url": "https://twitter.com/kesuke"}}''' def _GetSampleUser(self): return twitter.User(id=718443, name='Kesuke Miyagi', screen_name='kesuke', description=u'Canvas. JC Penny. Three ninety-eight.', location='Okinawa, Japan', url='https://twitter.com/kesuke', profile_image_url='https://twitter.com/system/user/pro' 'file_image/718443/normal/kesuke.pn' 'g') def _GetSampleStatus(self): return twitter.Status(created_at='Fri Jan 26 23:17:14 +0000 2007', id=4391023, text=u'A légpárnás hajóm tele van angolnákkal.', user=self._GetSampleUser()) def testInit(self): '''Test the twitter.Status constructor''' status = twitter.Status(created_at='Fri Jan 26 23:17:14 +0000 2007', id=4391023, text=u'A légpárnás hajóm tele van angolnákkal.', user=self._GetSampleUser()) def testGettersAndSetters(self): '''Test all of the twitter.Status getters and setters''' status = twitter.Status() status.SetId(4391023) self.assertEqual(4391023, status.GetId()) created_at = calendar.timegm((2007, 1, 26, 23, 17, 14, -1, -1, -1)) status.SetCreatedAt('Fri Jan 26 23:17:14 +0000 2007') self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', status.GetCreatedAt()) self.assertEqual(created_at, status.GetCreatedAtInSeconds()) status.SetNow(created_at + 10) self.assertEqual("about 10 seconds ago", status.GetRelativeCreatedAt()) status.SetText(u'A légpárnás hajóm tele van angolnákkal.') self.assertEqual(u'A légpárnás hajóm tele van angolnákkal.', status.GetText()) status.SetUser(self._GetSampleUser()) self.assertEqual(718443, status.GetUser().id) def testProperties(self): '''Test all of the twitter.Status properties''' status = twitter.Status() status.id = 1 self.assertEqual(1, status.id) created_at = calendar.timegm((2007, 1, 26, 23, 17, 14, -1, -1, -1)) status.created_at = 'Fri Jan 26 23:17:14 +0000 2007' self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', status.created_at) self.assertEqual(created_at, status.created_at_in_seconds) status.now = created_at + 10 self.assertEqual('about 10 seconds ago', status.relative_created_at) status.user = self._GetSampleUser() self.assertEqual(718443, status.user.id) def _ParseDate(self, string): return calendar.timegm(time.strptime(string, '%b %d %H:%M:%S %Y')) def testRelativeCreatedAt(self): '''Test various permutations of Status relative_created_at''' status = twitter.Status(created_at='Fri Jan 01 12:00:00 +0000 2007') status.now = self._ParseDate('Jan 01 12:00:00 2007') self.assertEqual('about a second ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:00:01 2007') self.assertEqual('about a second ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:00:02 2007') self.assertEqual('about 2 seconds ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:00:05 2007') self.assertEqual('about 5 seconds ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:00:50 2007') self.assertEqual('about a minute ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:01:00 2007') self.assertEqual('about a minute ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:01:10 2007') self.assertEqual('about a minute ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:02:00 2007') self.assertEqual('about 2 minutes ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:31:50 2007') self.assertEqual('about 31 minutes ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 12:50:00 2007') self.assertEqual('about an hour ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 13:00:00 2007') self.assertEqual('about an hour ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 13:10:00 2007') self.assertEqual('about an hour ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 14:00:00 2007') self.assertEqual('about 2 hours ago', status.relative_created_at) status.now = self._ParseDate('Jan 01 19:00:00 2007') self.assertEqual('about 7 hours ago', status.relative_created_at) status.now = self._ParseDate('Jan 02 11:30:00 2007') self.assertEqual('about a day ago', status.relative_created_at) status.now = self._ParseDate('Jan 04 12:00:00 2007') self.assertEqual('about 3 days ago', status.relative_created_at) status.now = self._ParseDate('Feb 04 12:00:00 2007') self.assertEqual('about 34 days ago', status.relative_created_at) def testAsJsonString(self): '''Test the twitter.Status AsJsonString method''' self.assertEqual(StatusTest.SAMPLE_JSON, self._GetSampleStatus().AsJsonString()) def testAsDict(self): '''Test the twitter.Status AsDict method''' status = self._GetSampleStatus() data = status.AsDict() self.assertEqual(4391023, data['id']) self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', data['created_at']) self.assertEqual(u'A légpárnás hajóm tele van angolnákkal.', data['text']) self.assertEqual(718443, data['user']['id']) def testEq(self): '''Test the twitter.Status __eq__ method''' status = twitter.Status() status.created_at = 'Fri Jan 26 23:17:14 +0000 2007' status.id = 4391023 status.text = u'A légpárnás hajóm tele van angolnákkal.' status.user = self._GetSampleUser() self.assertEqual(status, self._GetSampleStatus()) def testNewFromJsonDict(self): '''Test the twitter.Status NewFromJsonDict method''' data = simplejson.loads(StatusTest.SAMPLE_JSON) status = twitter.Status.NewFromJsonDict(data) self.assertEqual(self._GetSampleStatus(), status) class UserTest(unittest.TestCase): SAMPLE_JSON = '''{"description": "Indeterminate things", "id": 673483, "location": "San Francisco, CA", "name": "DeWitt", "profile_image_url": "https://twitter.com/system/user/profile_image/673483/normal/me.jpg", "screen_name": "dewitt", "status": {"created_at": "Fri Jan 26 17:28:19 +0000 2007", "id": 4212713, "text": "\\"Select all\\" and archive your Gmail inbox. The page loads so much faster!"}, "url": "http://unto.net/"}''' def _GetSampleStatus(self): return twitter.Status(created_at='Fri Jan 26 17:28:19 +0000 2007', id=4212713, text='"Select all" and archive your Gmail inbox. ' ' The page loads so much faster!') def _GetSampleUser(self): return twitter.User(id=673483, name='DeWitt', screen_name='dewitt', description=u'Indeterminate things', location='San Francisco, CA', url='http://unto.net/', profile_image_url='https://twitter.com/system/user/prof' 'ile_image/673483/normal/me.jpg', status=self._GetSampleStatus()) def testInit(self): '''Test the twitter.User constructor''' user = twitter.User(id=673483, name='DeWitt', screen_name='dewitt', description=u'Indeterminate things', url='https://twitter.com/dewitt', profile_image_url='https://twitter.com/system/user/prof' 'ile_image/673483/normal/me.jpg', status=self._GetSampleStatus()) def testGettersAndSetters(self): '''Test all of the twitter.User getters and setters''' user = twitter.User() user.SetId(673483) self.assertEqual(673483, user.GetId()) user.SetName('DeWitt') self.assertEqual('DeWitt', user.GetName()) user.SetScreenName('dewitt') self.assertEqual('dewitt', user.GetScreenName()) user.SetDescription('Indeterminate things') self.assertEqual('Indeterminate things', user.GetDescription()) user.SetLocation('San Francisco, CA') self.assertEqual('San Francisco, CA', user.GetLocation()) user.SetProfileImageUrl('https://twitter.com/system/user/profile_im' 'age/673483/normal/me.jpg') self.assertEqual('https://twitter.com/system/user/profile_image/673' '483/normal/me.jpg', user.GetProfileImageUrl()) user.SetStatus(self._GetSampleStatus()) self.assertEqual(4212713, user.GetStatus().id) def testProperties(self): '''Test all of the twitter.User properties''' user = twitter.User() user.id = 673483 self.assertEqual(673483, user.id) user.name = 'DeWitt' self.assertEqual('DeWitt', user.name) user.screen_name = 'dewitt' self.assertEqual('dewitt', user.screen_name) user.description = 'Indeterminate things' self.assertEqual('Indeterminate things', user.description) user.location = 'San Francisco, CA' self.assertEqual('San Francisco, CA', user.location) user.profile_image_url = 'https://twitter.com/system/user/profile_i' \ 'mage/673483/normal/me.jpg' self.assertEqual('https://twitter.com/system/user/profile_image/6734' '83/normal/me.jpg', user.profile_image_url) self.status = self._GetSampleStatus() self.assertEqual(4212713, self.status.id) def testAsJsonString(self): '''Test the twitter.User AsJsonString method''' self.assertEqual(UserTest.SAMPLE_JSON, self._GetSampleUser().AsJsonString()) def testAsDict(self): '''Test the twitter.User AsDict method''' user = self._GetSampleUser() data = user.AsDict() self.assertEqual(673483, data['id']) self.assertEqual('DeWitt', data['name']) self.assertEqual('dewitt', data['screen_name']) self.assertEqual('Indeterminate things', data['description']) self.assertEqual('San Francisco, CA', data['location']) self.assertEqual('https://twitter.com/system/user/profile_image/6734' '83/normal/me.jpg', data['profile_image_url']) self.assertEqual('http://unto.net/', data['url']) self.assertEqual(4212713, data['status']['id']) def testEq(self): '''Test the twitter.User __eq__ method''' user = twitter.User() user.id = 673483 user.name = 'DeWitt' user.screen_name = 'dewitt' user.description = 'Indeterminate things' user.location = 'San Francisco, CA' user.profile_image_url = 'https://twitter.com/system/user/profile_image/67' \ '3483/normal/me.jpg' user.url = 'http://unto.net/' user.status = self._GetSampleStatus() self.assertEqual(user, self._GetSampleUser()) def testNewFromJsonDict(self): '''Test the twitter.User NewFromJsonDict method''' data = simplejson.loads(UserTest.SAMPLE_JSON) user = twitter.User.NewFromJsonDict(data) self.assertEqual(self._GetSampleUser(), user) class TrendTest(unittest.TestCase): SAMPLE_JSON = '''{"name": "Kesuke Miyagi", "query": "Kesuke Miyagi"}''' def _GetSampleTrend(self): return twitter.Trend(name='Kesuke Miyagi', query='Kesuke Miyagi', timestamp='Fri Jan 26 23:17:14 +0000 2007') def testInit(self): '''Test the twitter.Trend constructor''' trend = twitter.Trend(name='Kesuke Miyagi', query='Kesuke Miyagi', timestamp='Fri Jan 26 23:17:14 +0000 2007') def testProperties(self): '''Test all of the twitter.Trend properties''' trend = twitter.Trend() trend.name = 'Kesuke Miyagi' self.assertEqual('Kesuke Miyagi', trend.name) trend.query = 'Kesuke Miyagi' self.assertEqual('Kesuke Miyagi', trend.query) trend.timestamp = 'Fri Jan 26 23:17:14 +0000 2007' self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', trend.timestamp) def testNewFromJsonDict(self): '''Test the twitter.Trend NewFromJsonDict method''' data = simplejson.loads(TrendTest.SAMPLE_JSON) trend = twitter.Trend.NewFromJsonDict(data, timestamp='Fri Jan 26 23:17:14 +0000 2007') self.assertEqual(self._GetSampleTrend(), trend) def testEq(self): '''Test the twitter.Trend __eq__ method''' trend = twitter.Trend() trend.name = 'Kesuke Miyagi' trend.query = 'Kesuke Miyagi' trend.timestamp = 'Fri Jan 26 23:17:14 +0000 2007' self.assertEqual(trend, self._GetSampleTrend()) class FileCacheTest(unittest.TestCase): def testInit(self): """Test the twitter._FileCache constructor""" cache = twitter._FileCache() self.assert_(cache is not None, 'cache is None') def testSet(self): """Test the twitter._FileCache.Set method""" cache = twitter._FileCache() cache.Set("foo",'Hello World!') cache.Remove("foo") def testRemove(self): """Test the twitter._FileCache.Remove method""" cache = twitter._FileCache() cache.Set("foo",'Hello World!') cache.Remove("foo") data = cache.Get("foo") self.assertEqual(data, None, 'data is not None') def testGet(self): """Test the twitter._FileCache.Get method""" cache = twitter._FileCache() cache.Set("foo",'Hello World!') data = cache.Get("foo") self.assertEqual('Hello World!', data) cache.Remove("foo") def testGetCachedTime(self): """Test the twitter._FileCache.GetCachedTime method""" now = time.time() cache = twitter._FileCache() cache.Set("foo",'Hello World!') cached_time = cache.GetCachedTime("foo") delta = cached_time - now self.assert_(delta <= 1, 'Cached time differs from clock time by more than 1 second.') cache.Remove("foo") class ApiTest(unittest.TestCase): def setUp(self): self._urllib = MockUrllib() api = twitter.Api(consumer_key='CONSUMER_KEY', consumer_secret='CONSUMER_SECRET', access_token_key='OAUTH_TOKEN', access_token_secret='OAUTH_SECRET', cache=None) api.SetUrllib(self._urllib) self._api = api def testTwitterError(self): '''Test that twitter responses containing an error message are wrapped.''' self._AddHandler('https://api.twitter.com/1/statuses/public_timeline.json', curry(self._OpenTestData, 'public_timeline_error.json')) # Manually try/catch so we can check the exception's value try: statuses = self._api.GetPublicTimeline() except twitter.TwitterError, error: # If the error message matches, the test passes self.assertEqual('test error', error.message) else: self.fail('TwitterError expected') def testGetPublicTimeline(self): '''Test the twitter.Api GetPublicTimeline method''' self._AddHandler('https://api.twitter.com/1/statuses/public_timeline.json?since_id=12345', curry(self._OpenTestData, 'public_timeline.json')) statuses = self._api.GetPublicTimeline(since_id=12345) # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(20, len(statuses)) self.assertEqual(89497702, statuses[0].id) def testGetUserTimeline(self): '''Test the twitter.Api GetUserTimeline method''' self._AddHandler('https://api.twitter.com/1/statuses/user_timeline/kesuke.json?count=1', curry(self._OpenTestData, 'user_timeline-kesuke.json')) statuses = self._api.GetUserTimeline('kesuke', count=1) # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(89512102, statuses[0].id) self.assertEqual(718443, statuses[0].user.id) def testGetFriendsTimeline(self): '''Test the twitter.Api GetFriendsTimeline method''' self._AddHandler('https://api.twitter.com/1/statuses/friends_timeline/kesuke.json', curry(self._OpenTestData, 'friends_timeline-kesuke.json')) statuses = self._api.GetFriendsTimeline('kesuke') # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(20, len(statuses)) self.assertEqual(718443, statuses[0].user.id) def testGetStatus(self): '''Test the twitter.Api GetStatus method''' self._AddHandler('https://api.twitter.com/1/statuses/show/89512102.json', curry(self._OpenTestData, 'show-89512102.json')) status = self._api.GetStatus(89512102) self.assertEqual(89512102, status.id) self.assertEqual(718443, status.user.id) def testDestroyStatus(self): '''Test the twitter.Api DestroyStatus method''' self._AddHandler('https://api.twitter.com/1/statuses/destroy/103208352.json', curry(self._OpenTestData, 'status-destroy.json')) status = self._api.DestroyStatus(103208352) self.assertEqual(103208352, status.id) def testPostUpdate(self): '''Test the twitter.Api PostUpdate method''' self._AddHandler('https://api.twitter.com/1/statuses/update.json', curry(self._OpenTestData, 'update.json')) status = self._api.PostUpdate(u'Моё судно на воздушной подушке полно угрей'.encode('utf8')) # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text) def testGetReplies(self): '''Test the twitter.Api GetReplies method''' self._AddHandler('https://api.twitter.com/1/statuses/replies.json?page=1', curry(self._OpenTestData, 'replies.json')) statuses = self._api.GetReplies(page=1) self.assertEqual(36657062, statuses[0].id) def testGetFriends(self): '''Test the twitter.Api GetFriends method''' self._AddHandler('https://api.twitter.com/1/statuses/friends.json?cursor=123', curry(self._OpenTestData, 'friends.json')) users = self._api.GetFriends(cursor=123) buzz = [u.status for u in users if u.screen_name == 'buzz'] self.assertEqual(89543882, buzz[0].id) def testGetFollowers(self): '''Test the twitter.Api GetFollowers method''' self._AddHandler('https://api.twitter.com/1/statuses/followers.json?page=1', curry(self._OpenTestData, 'followers.json')) users = self._api.GetFollowers(page=1) # This is rather arbitrary, but spot checking is better than nothing alexkingorg = [u.status for u in users if u.screen_name == 'alexkingorg'] self.assertEqual(89554432, alexkingorg[0].id) def testGetFeatured(self): '''Test the twitter.Api GetFeatured method''' self._AddHandler('https://api.twitter.com/1/statuses/featured.json', curry(self._OpenTestData, 'featured.json')) users = self._api.GetFeatured() # This is rather arbitrary, but spot checking is better than nothing stevenwright = [u.status for u in users if u.screen_name == 'stevenwright'] self.assertEqual(86991742, stevenwright[0].id) def testGetDirectMessages(self): '''Test the twitter.Api GetDirectMessages method''' self._AddHandler('https://api.twitter.com/1/direct_messages.json?page=1', curry(self._OpenTestData, 'direct_messages.json')) statuses = self._api.GetDirectMessages(page=1) self.assertEqual(u'A légpárnás hajóm tele van angolnákkal.', statuses[0].text) def testPostDirectMessage(self): '''Test the twitter.Api PostDirectMessage method''' self._AddHandler('https://api.twitter.com/1/direct_messages/new.json', curry(self._OpenTestData, 'direct_messages-new.json')) status = self._api.PostDirectMessage('test', u'Моё судно на воздушной подушке полно угрей'.encode('utf8')) # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text) def testDestroyDirectMessage(self): '''Test the twitter.Api DestroyDirectMessage method''' self._AddHandler('https://api.twitter.com/1/direct_messages/destroy/3496342.json', curry(self._OpenTestData, 'direct_message-destroy.json')) status = self._api.DestroyDirectMessage(3496342) # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(673483, status.sender_id) def testCreateFriendship(self): '''Test the twitter.Api CreateFriendship method''' self._AddHandler('https://api.twitter.com/1/friendships/create/dewitt.json', curry(self._OpenTestData, 'friendship-create.json')) user = self._api.CreateFriendship('dewitt') # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(673483, user.id) def testDestroyFriendship(self): '''Test the twitter.Api DestroyFriendship method''' self._AddHandler('https://api.twitter.com/1/friendships/destroy/dewitt.json', curry(self._OpenTestData, 'friendship-destroy.json')) user = self._api.DestroyFriendship('dewitt') # This is rather arbitrary, but spot checking is better than nothing self.assertEqual(673483, user.id) def testGetUser(self): '''Test the twitter.Api GetUser method''' self._AddHandler('https://api.twitter.com/1/users/show/dewitt.json', curry(self._OpenTestData, 'show-dewitt.json')) user = self._api.GetUser('dewitt') self.assertEqual('dewitt', user.screen_name) self.assertEqual(89586072, user.status.id) def _AddHandler(self, url, callback): self._urllib.AddHandler(url, callback) def _GetTestDataPath(self, filename): directory = os.path.dirname(os.path.abspath(__file__)) test_data_dir = os.path.join(directory, 'testdata') return os.path.join(test_data_dir, filename) def _OpenTestData(self, filename): f = open(self._GetTestDataPath(filename)) # make sure that the returned object contains an .info() method: # headers are set to {} return urllib.addinfo(f, {}) class MockUrllib(object): '''A mock replacement for urllib that hardcodes specific responses.''' def __init__(self): self._handlers = {} self.HTTPBasicAuthHandler = MockHTTPBasicAuthHandler def AddHandler(self, url, callback): self._handlers[url] = callback def build_opener(self, *handlers): return MockOpener(self._handlers) def HTTPHandler(self, *args, **kwargs): return None def HTTPSHandler(self, *args, **kwargs): return None def OpenerDirector(self): return self.build_opener() class MockOpener(object): '''A mock opener for urllib''' def __init__(self, handlers): self._handlers = handlers self._opened = False def open(self, url, data=None): if self._opened: raise Exception('MockOpener already opened.') # Remove parameters from URL - they're only added by oauth and we # don't want to test oauth if '?' in url: # We split using & and filter on the beginning of each key # This is crude but we have to keep the ordering for now (url, qs) = url.split('?') tokens = [token for token in qs.split('&') if not token.startswith('oauth')] if len(tokens) > 0: url = "%s?%s"%(url, '&'.join(tokens)) if url in self._handlers: self._opened = True return self._handlers[url]() else: raise Exception('Unexpected URL %s (Checked: %s)' % (url, self._handlers)) def add_handler(self, *args, **kwargs): pass def close(self): if not self._opened: raise Exception('MockOpener closed before it was opened.') self._opened = False class MockHTTPBasicAuthHandler(object): '''A mock replacement for HTTPBasicAuthHandler''' def add_password(self, realm, uri, user, passwd): # TODO(dewitt): Add verification that the proper args are passed pass class curry: # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549 def __init__(self, fun, *args, **kwargs): self.fun = fun self.pending = args[:] self.kwargs = kwargs.copy() def __call__(self, *args, **kwargs): if kwargs and self.kwargs: kw = self.kwargs.copy() kw.update(kwargs) else: kw = kwargs or self.kwargs return self.fun(*(self.pending + args), **kw) def suite(): suite = unittest.TestSuite() suite.addTests(unittest.makeSuite(FileCacheTest)) suite.addTests(unittest.makeSuite(StatusTest)) suite.addTests(unittest.makeSuite(UserTest)) suite.addTests(unittest.makeSuite(ApiTest)) return suite if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python2.4 '''Load the latest update for a Twitter user and leave it in an XHTML fragment''' __author__ = 'dewitt@google.com' import codecs import getopt import sys import twitter TEMPLATE = """ <div class="twitter"> <span class="twitter-user"><a href="http://twitter.com/%s">Twitter</a>: </span> <span class="twitter-text">%s</span> <span class="twitter-relative-created-at"><a href="http://twitter.com/%s/statuses/%s">Posted %s</a></span> </div> """ def Usage(): print 'Usage: %s [options] twitterid' % __file__ print print ' This script fetches a users latest twitter update and stores' print ' the result in a file as an XHTML fragment' print print ' Options:' print ' --help -h : print this help' print ' --output : the output file [default: stdout]' def FetchTwitter(user, output): assert user statuses = twitter.Api().GetUserTimeline(user=user, count=1) s = statuses[0] xhtml = TEMPLATE % (s.user.screen_name, s.text, s.user.screen_name, s.id, s.relative_created_at) if output: Save(xhtml, output) else: print xhtml def Save(xhtml, output): out = codecs.open(output, mode='w', encoding='ascii', errors='xmlcharrefreplace') out.write(xhtml) out.close() def main(): try: opts, args = getopt.gnu_getopt(sys.argv[1:], 'ho', ['help', 'output=']) except getopt.GetoptError: Usage() sys.exit(2) try: user = args[0] except: Usage() sys.exit(2) output = None for o, a in opts: if o in ("-h", "--help"): Usage() sys.exit(2) if o in ("-o", "--output"): output = a FetchTwitter(user, output) if __name__ == "__main__": main()
Python
#!/usr/bin/python2.4 '''Post a message to twitter''' __author__ = 'dewitt@google.com' import ConfigParser import getopt import os import sys import twitter USAGE = '''Usage: tweet [options] message This script posts a message to Twitter. Options: -h --help : print this help --consumer-key : the twitter consumer key --consumer-secret : the twitter consumer secret --access-key : the twitter access token key --access-secret : the twitter access token secret --encoding : the character set encoding used in input strings, e.g. "utf-8". [optional] Documentation: If either of the command line flags are not present, the environment variables TWEETUSERNAME and TWEETPASSWORD will then be checked for your consumer_key or consumer_secret, respectively. If neither the command line flags nor the enviroment variables are present, the .tweetrc file, if it exists, can be used to set the default consumer_key and consumer_secret. The file should contain the following three lines, replacing *consumer_key* with your consumer key, and *consumer_secret* with your consumer secret: A skeletal .tweetrc file: [Tweet] consumer_key: *consumer_key* consumer_secret: *consumer_password* access_key: *access_key* access_secret: *access_password* ''' def PrintUsageAndExit(): print USAGE sys.exit(2) def GetConsumerKeyEnv(): return os.environ.get("TWEETUSERNAME", None) def GetConsumerSecretEnv(): return os.environ.get("TWEETPASSWORD", None) def GetAccessKeyEnv(): return os.environ.get("TWEETACCESSKEY", None) def GetAccessSecretEnv(): return os.environ.get("TWEETACCESSSECRET", None) class TweetRc(object): def __init__(self): self._config = None def GetConsumerKey(self): return self._GetOption('consumer_key') def GetConsumerSecret(self): return self._GetOption('consumer_secret') def GetAccessKey(self): return self._GetOption('access_key') def GetAccessSecret(self): return self._GetOption('access_secret') def _GetOption(self, option): try: return self._GetConfig().get('Tweet', option) except: return None def _GetConfig(self): if not self._config: self._config = ConfigParser.ConfigParser() self._config.read(os.path.expanduser('~/.tweetrc')) return self._config def main(): try: shortflags = 'h' longflags = ['help', 'consumer-key=', 'consumer-secret=', 'access-key=', 'access-secret=', 'encoding='] opts, args = getopt.gnu_getopt(sys.argv[1:], shortflags, longflags) except getopt.GetoptError: PrintUsageAndExit() consumer_keyflag = None consumer_secretflag = None access_keyflag = None access_secretflag = None encoding = None for o, a in opts: if o in ("-h", "--help"): PrintUsageAndExit() if o in ("--consumer-key"): consumer_keyflag = a if o in ("--consumer-secret"): consumer_secretflag = a if o in ("--access-key"): access_keyflag = a if o in ("--access-secret"): access_secretflag = a if o in ("--encoding"): encoding = a message = ' '.join(args) if not message: PrintUsageAndExit() rc = TweetRc() consumer_key = consumer_keyflag or GetConsumerKeyEnv() or rc.GetConsumerKey() consumer_secret = consumer_secretflag or GetConsumerSecretEnv() or rc.GetConsumerSecret() access_key = access_keyflag or GetAccessKeyEnv() or rc.GetAccessKey() access_secret = access_secretflag or GetAccessSecretEnv() or rc.GetAccessSecret() if not consumer_key or not consumer_secret or not access_key or not access_secret: PrintUsageAndExit() api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_key, access_token_secret=access_secret, input_encoding=encoding) try: status = api.PostUpdate(message) except UnicodeDecodeError: print "Your message could not be encoded. Perhaps it contains non-ASCII characters? " print "Try explicitly specifying the encoding with the --encoding flag" sys.exit(2) print "%s just posted: %s" % (status.user.name, status.text) if __name__ == "__main__": main()
Python
#!/usr/bin/python2.4 # # Copyright 2007 The Python-Twitter Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''A class that defines the default URL Shortener. TinyURL is provided as the default and as an example. ''' import urllib # Change History # # 2010-05-16 # TinyURL example and the idea for this comes from a bug filed by # acolorado with patch provided by ghills. Class implementation # was done by bear. # # Issue 19 http://code.google.com/p/python-twitter/issues/detail?id=19 # class ShortenURL(object): '''Helper class to make URL Shortener calls if/when required''' def __init__(self, userid=None, password=None): '''Instantiate a new ShortenURL object Args: userid: userid for any required authorization call [optional] password: password for any required authorization call [optional] ''' self.userid = userid self.password = password def Shorten(self, longURL): '''Call TinyURL API and returned shortened URL result Args: longURL: URL string to shorten Returns: The shortened URL as a string Note: longURL is required and no checks are made to ensure completeness ''' result = None f = urllib.urlopen("http://tinyurl.com/api-create.php?url=%s" % longURL) try: result = f.read() finally: f.close() return result
Python
#!/usr/bin/python2.4 # # Copyright 2007 The Python-Twitter Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''The setup and build script for the python-twitter library.''' __author__ = 'python-twitter@googlegroups.com' __version__ = '0.8.3' # The base package metadata to be used by both distutils and setuptools METADATA = dict( name = "python-twitter", version = __version__, py_modules = ['twitter'], author='The Python-Twitter Developers', author_email='python-twitter@googlegroups.com', description='A python wrapper around the Twitter API', license='Apache License 2.0', url='http://code.google.com/p/python-twitter/', keywords='twitter api', ) # Extra package metadata to be used only if setuptools is installed SETUPTOOLS_METADATA = dict( install_requires = ['setuptools', 'simplejson', 'oauth2'], include_package_data = True, classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Communications :: Chat', 'Topic :: Internet', ], test_suite = 'twitter_test.suite', ) def Read(file): return open(file).read() def BuildLongDescription(): return '\n'.join([Read('README'), Read('CHANGES')]) def Main(): # Build the long_description from the README and CHANGES METADATA['long_description'] = BuildLongDescription() # Use setuptools if available, otherwise fallback and use distutils try: import setuptools METADATA.update(SETUPTOOLS_METADATA) setuptools.setup(**METADATA) except ImportError: import distutils.core distutils.core.setup(**METADATA) if __name__ == '__main__': Main()
Python
"""Implementation of JSONDecoder """ import re import sys import struct from simplejson.scanner import make_scanner try: from simplejson._speedups import scanstring as c_scanstring except ImportError: c_scanstring = None __all__ = ['JSONDecoder'] FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL def _floatconstants(): _BYTES = '7FF80000000000007FF0000000000000'.decode('hex') if sys.byteorder != 'big': _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1] nan, inf = struct.unpack('dd', _BYTES) return nan, inf, -inf NaN, PosInf, NegInf = _floatconstants() def linecol(doc, pos): lineno = doc.count('\n', 0, pos) + 1 if lineno == 1: colno = pos else: colno = pos - doc.rindex('\n', 0, pos) return lineno, colno def errmsg(msg, doc, pos, end=None): # Note that this function is called from _speedups lineno, colno = linecol(doc, pos) if end is None: return '%s: line %d column %d (char %d)' % (msg, lineno, colno, pos) endlineno, endcolno = linecol(doc, end) return '%s: line %d column %d - line %d column %d (char %d - %d)' % ( msg, lineno, colno, endlineno, endcolno, pos, end) _CONSTANTS = { '-Infinity': NegInf, 'Infinity': PosInf, 'NaN': NaN, } STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS) BACKSLASH = { '"': u'"', '\\': u'\\', '/': u'/', 'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t', } DEFAULT_ENCODING = "utf-8" def py_scanstring(s, end, encoding=None, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match): """Scan the string s for a JSON string. End is the index of the character in s after the quote that started the JSON string. Unescapes all valid JSON string escape sequences and raises ValueError on attempt to decode an invalid string. If strict is False then literal control characters are allowed in the string. Returns a tuple of the decoded string and the index of the character in s after the end quote.""" if encoding is None: encoding = DEFAULT_ENCODING chunks = [] _append = chunks.append begin = end - 1 while 1: chunk = _m(s, end) if chunk is None: raise ValueError( errmsg("Unterminated string starting at", s, begin)) end = chunk.end() content, terminator = chunk.groups() # Content is contains zero or more unescaped string characters if content: if not isinstance(content, unicode): content = unicode(content, encoding) _append(content) # Terminator is the end of string, a literal control character, # or a backslash denoting that an escape sequence follows if terminator == '"': break elif terminator != '\\': if strict: msg = "Invalid control character %r at" % (terminator,) raise ValueError(msg, s, end) else: _append(terminator) continue try: esc = s[end] except IndexError: raise ValueError( errmsg("Unterminated string starting at", s, begin)) # If not a unicode escape sequence, must be in the lookup table if esc != 'u': try: char = _b[esc] except KeyError: raise ValueError( errmsg("Invalid \\escape: %r" % (esc,), s, end)) end += 1 else: # Unicode escape sequence esc = s[end + 1:end + 5] next_end = end + 5 if len(esc) != 4: msg = "Invalid \\uXXXX escape" raise ValueError(errmsg(msg, s, end)) uni = int(esc, 16) # Check for surrogate pair on UCS-4 systems if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535: msg = "Invalid \\uXXXX\\uXXXX surrogate pair" if not s[end + 5:end + 7] == '\\u': raise ValueError(errmsg(msg, s, end)) esc2 = s[end + 7:end + 11] if len(esc2) != 4: raise ValueError(errmsg(msg, s, end)) uni2 = int(esc2, 16) uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00)) next_end += 6 char = unichr(uni) end = next_end # Append the unescaped character _append(char) return u''.join(chunks), end # Use speedup if available scanstring = c_scanstring or py_scanstring WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS) WHITESPACE_STR = ' \t\n\r' def JSONObject((s, end), encoding, strict, scan_once, object_hook, _w=WHITESPACE.match, _ws=WHITESPACE_STR): pairs = {} # Use a slice to prevent IndexError from being raised, the following # check will raise a more specific ValueError if the string is empty nextchar = s[end:end + 1] # Normally we expect nextchar == '"' if nextchar != '"': if nextchar in _ws: end = _w(s, end).end() nextchar = s[end:end + 1] # Trivial empty object if nextchar == '}': return pairs, end + 1 elif nextchar != '"': raise ValueError(errmsg("Expecting property name", s, end)) end += 1 while True: key, end = scanstring(s, end, encoding, strict) # To skip some function call overhead we optimize the fast paths where # the JSON key separator is ": " or just ":". if s[end:end + 1] != ':': end = _w(s, end).end() if s[end:end + 1] != ':': raise ValueError(errmsg("Expecting : delimiter", s, end)) end += 1 try: if s[end] in _ws: end += 1 if s[end] in _ws: end = _w(s, end + 1).end() except IndexError: pass try: value, end = scan_once(s, end) except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) pairs[key] = value try: nextchar = s[end] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end] except IndexError: nextchar = '' end += 1 if nextchar == '}': break elif nextchar != ',': raise ValueError(errmsg("Expecting , delimiter", s, end - 1)) try: nextchar = s[end] if nextchar in _ws: end += 1 nextchar = s[end] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end] except IndexError: nextchar = '' end += 1 if nextchar != '"': raise ValueError(errmsg("Expecting property name", s, end - 1)) if object_hook is not None: pairs = object_hook(pairs) return pairs, end def JSONArray((s, end), scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR): values = [] nextchar = s[end:end + 1] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end:end + 1] # Look-ahead for trivial empty array if nextchar == ']': return values, end + 1 _append = values.append while True: try: value, end = scan_once(s, end) except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) _append(value) nextchar = s[end:end + 1] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end:end + 1] end += 1 if nextchar == ']': break elif nextchar != ',': raise ValueError(errmsg("Expecting , delimiter", s, end)) try: if s[end] in _ws: end += 1 if s[end] in _ws: end = _w(s, end + 1).end() except IndexError: pass return values, end class JSONDecoder(object): """Simple JSON <http://json.org> decoder Performs the following translations in decoding by default: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | +---------------+-------------------+ | string | unicode | +---------------+-------------------+ | number (int) | int, long | +---------------+-------------------+ | number (real) | float | +---------------+-------------------+ | true | True | +---------------+-------------------+ | false | False | +---------------+-------------------+ | null | None | +---------------+-------------------+ It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their corresponding ``float`` values, which is outside the JSON spec. """ def __init__(self, encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True): """``encoding`` determines the encoding used to interpret any ``str`` objects decoded by this instance (utf-8 by default). It has no effect when decoding ``unicode`` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as ``unicode``. ``object_hook``, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given ``dict``. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered. """ self.encoding = encoding self.object_hook = object_hook self.parse_float = parse_float or float self.parse_int = parse_int or int self.parse_constant = parse_constant or _CONSTANTS.__getitem__ self.strict = strict self.parse_object = JSONObject self.parse_array = JSONArray self.parse_string = scanstring self.scan_once = make_scanner(self) def decode(self, s, _w=WHITESPACE.match): """Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) """ obj, end = self.raw_decode(s, idx=_w(s, 0).end()) end = _w(s, end).end() if end != len(s): raise ValueError(errmsg("Extra data", s, end, len(s))) return obj def raw_decode(self, s, idx=0): """Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end. """ try: obj, end = self.scan_once(s, idx) except StopIteration: raise ValueError("No JSON object could be decoded") return obj, end
Python
"""JSON token scanner """ import re try: from simplejson._speedups import make_scanner as c_make_scanner except ImportError: c_make_scanner = None __all__ = ['make_scanner'] NUMBER_RE = re.compile( r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?', (re.VERBOSE | re.MULTILINE | re.DOTALL)) def py_make_scanner(context): parse_object = context.parse_object parse_array = context.parse_array parse_string = context.parse_string match_number = NUMBER_RE.match encoding = context.encoding strict = context.strict parse_float = context.parse_float parse_int = context.parse_int parse_constant = context.parse_constant object_hook = context.object_hook def _scan_once(string, idx): try: nextchar = string[idx] except IndexError: raise StopIteration if nextchar == '"': return parse_string(string, idx + 1, encoding, strict) elif nextchar == '{': return parse_object((string, idx + 1), encoding, strict, _scan_once, object_hook) elif nextchar == '[': return parse_array((string, idx + 1), _scan_once) elif nextchar == 'n' and string[idx:idx + 4] == 'null': return None, idx + 4 elif nextchar == 't' and string[idx:idx + 4] == 'true': return True, idx + 4 elif nextchar == 'f' and string[idx:idx + 5] == 'false': return False, idx + 5 m = match_number(string, idx) if m is not None: integer, frac, exp = m.groups() if frac or exp: res = parse_float(integer + (frac or '') + (exp or '')) else: res = parse_int(integer) return res, m.end() elif nextchar == 'N' and string[idx:idx + 3] == 'NaN': return parse_constant('NaN'), idx + 3 elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity': return parse_constant('Infinity'), idx + 8 elif nextchar == '-' and string[idx:idx + 9] == '-Infinity': return parse_constant('-Infinity'), idx + 9 else: raise StopIteration return _scan_once make_scanner = c_make_scanner or py_make_scanner
Python
"""Implementation of JSONEncoder """ import re try: from simplejson._speedups import encode_basestring_ascii as c_encode_basestring_ascii except ImportError: c_encode_basestring_ascii = None try: from simplejson._speedups import make_encoder as c_make_encoder except ImportError: c_make_encoder = None ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])') HAS_UTF8 = re.compile(r'[\x80-\xff]') ESCAPE_DCT = { '\\': '\\\\', '"': '\\"', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', } for i in range(0x20): ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,)) # Assume this produces an infinity on all machines (probably not guaranteed) INFINITY = float('1e66666') FLOAT_REPR = repr def encode_basestring(s): """Return a JSON representation of a Python string """ def replace(match): return ESCAPE_DCT[match.group(0)] return '"' + ESCAPE.sub(replace, s) + '"' def py_encode_basestring_ascii(s): """Return an ASCII-only JSON representation of a Python string """ if isinstance(s, str) and HAS_UTF8.search(s) is not None: s = s.decode('utf-8') def replace(match): s = match.group(0) try: return ESCAPE_DCT[s] except KeyError: n = ord(s) if n < 0x10000: return '\\u%04x' % (n,) else: # surrogate pair n -= 0x10000 s1 = 0xd800 | ((n >> 10) & 0x3ff) s2 = 0xdc00 | (n & 0x3ff) return '\\u%04x\\u%04x' % (s1, s2) return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"' encode_basestring_ascii = c_encode_basestring_ascii or py_encode_basestring_ascii class JSONEncoder(object): """Extensible JSON <http://json.org> encoder for Python data structures. Supports the following objects and types by default: +-------------------+---------------+ | Python | JSON | +===================+===============+ | dict | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str, unicode | string | +-------------------+---------------+ | int, long, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null | +-------------------+---------------+ To extend this to recognize other objects, subclass and implement a ``.default()`` method with another method that returns a serializable object for ``o`` if possible, otherwise it should call the superclass implementation (to raise ``TypeError``). """ item_separator = ', ' key_separator = ': ' def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None): """Constructor for JSONEncoder, with sensible defaults. If skipkeys is False, then it is a TypeError to attempt encoding of keys that are not str, int, long, float or None. If skipkeys is True, such items are simply skipped. If ensure_ascii is True, the output is guaranteed to be str objects with all incoming unicode characters escaped. If ensure_ascii is false, the output will be unicode object. If check_circular is True, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place. If allow_nan is True, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats. If sort_keys is True, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation. If specified, separators should be a (item_separator, key_separator) tuple. The default is (', ', ': '). To get the most compact JSON representation you should specify (',', ':') to eliminate whitespace. If specified, default is a function that gets called for objects that can't otherwise be serialized. It should return a JSON encodable version of the object or raise a ``TypeError``. If encoding is not None, then all input strings will be transformed into unicode using that encoding prior to JSON-encoding. The default is UTF-8. """ self.skipkeys = skipkeys self.ensure_ascii = ensure_ascii self.check_circular = check_circular self.allow_nan = allow_nan self.sort_keys = sort_keys self.indent = indent if separators is not None: self.item_separator, self.key_separator = separators if default is not None: self.default = default self.encoding = encoding def default(self, o): """Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, o) """ raise TypeError("%r is not JSON serializable" % (o,)) def encode(self, o): """Return a JSON string representation of a Python data structure. >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}' """ # This is for extremely simple cases and benchmarks. if isinstance(o, basestring): if isinstance(o, str): _encoding = self.encoding if (_encoding is not None and not (_encoding == 'utf-8')): o = o.decode(_encoding) if self.ensure_ascii: return encode_basestring_ascii(o) else: return encode_basestring(o) # This doesn't pass the iterator directly to ''.join() because the # exceptions aren't as detailed. The list call should be roughly # equivalent to the PySequence_Fast that ''.join() would do. chunks = self.iterencode(o, _one_shot=True) if not isinstance(chunks, (list, tuple)): chunks = list(chunks) return ''.join(chunks) def iterencode(self, o, _one_shot=False): """Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) """ if self.check_circular: markers = {} else: markers = None if self.ensure_ascii: _encoder = encode_basestring_ascii else: _encoder = encode_basestring if self.encoding != 'utf-8': def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding): if isinstance(o, str): o = o.decode(_encoding) return _orig_encoder(o) def floatstr(o, allow_nan=self.allow_nan, _repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY): # Check for specials. Note that this type of test is processor- and/or # platform-specific, so do tests which don't depend on the internals. if o != o: text = 'NaN' elif o == _inf: text = 'Infinity' elif o == _neginf: text = '-Infinity' else: return _repr(o) if not allow_nan: raise ValueError("Out of range float values are not JSON compliant: %r" % (o,)) return text if _one_shot and c_make_encoder is not None and not self.indent and not self.sort_keys: _iterencode = c_make_encoder( markers, self.default, _encoder, self.indent, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, self.allow_nan) else: _iterencode = _make_iterencode( markers, self.default, _encoder, self.indent, floatstr, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, _one_shot) return _iterencode(o, 0) def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot, ## HACK: hand-optimized bytecode; turn globals into locals False=False, True=True, ValueError=ValueError, basestring=basestring, dict=dict, float=float, id=id, int=int, isinstance=isinstance, list=list, long=long, str=str, tuple=tuple, ): def _iterencode_list(lst, _current_indent_level): if not lst: yield '[]' return if markers is not None: markerid = id(lst) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = lst buf = '[' if _indent is not None: _current_indent_level += 1 newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) separator = _item_separator + newline_indent buf += newline_indent else: newline_indent = None separator = _item_separator first = True for value in lst: if first: first = False else: buf = separator if isinstance(value, basestring): yield buf + _encoder(value) elif value is None: yield buf + 'null' elif value is True: yield buf + 'true' elif value is False: yield buf + 'false' elif isinstance(value, (int, long)): yield buf + str(value) elif isinstance(value, float): yield buf + _floatstr(value) else: yield buf if isinstance(value, (list, tuple)): chunks = _iterencode_list(value, _current_indent_level) elif isinstance(value, dict): chunks = _iterencode_dict(value, _current_indent_level) else: chunks = _iterencode(value, _current_indent_level) for chunk in chunks: yield chunk if newline_indent is not None: _current_indent_level -= 1 yield '\n' + (' ' * (_indent * _current_indent_level)) yield ']' if markers is not None: del markers[markerid] def _iterencode_dict(dct, _current_indent_level): if not dct: yield '{}' return if markers is not None: markerid = id(dct) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = dct yield '{' if _indent is not None: _current_indent_level += 1 newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) item_separator = _item_separator + newline_indent yield newline_indent else: newline_indent = None item_separator = _item_separator first = True if _sort_keys: items = dct.items() items.sort(key=lambda kv: kv[0]) else: items = dct.iteritems() for key, value in items: if isinstance(key, basestring): pass # JavaScript is weakly typed for these, so it makes sense to # also allow them. Many encoders seem to do something like this. elif isinstance(key, float): key = _floatstr(key) elif isinstance(key, (int, long)): key = str(key) elif key is True: key = 'true' elif key is False: key = 'false' elif key is None: key = 'null' elif _skipkeys: continue else: raise TypeError("key %r is not a string" % (key,)) if first: first = False else: yield item_separator yield _encoder(key) yield _key_separator if isinstance(value, basestring): yield _encoder(value) elif value is None: yield 'null' elif value is True: yield 'true' elif value is False: yield 'false' elif isinstance(value, (int, long)): yield str(value) elif isinstance(value, float): yield _floatstr(value) else: if isinstance(value, (list, tuple)): chunks = _iterencode_list(value, _current_indent_level) elif isinstance(value, dict): chunks = _iterencode_dict(value, _current_indent_level) else: chunks = _iterencode(value, _current_indent_level) for chunk in chunks: yield chunk if newline_indent is not None: _current_indent_level -= 1 yield '\n' + (' ' * (_indent * _current_indent_level)) yield '}' if markers is not None: del markers[markerid] def _iterencode(o, _current_indent_level): if isinstance(o, basestring): yield _encoder(o) elif o is None: yield 'null' elif o is True: yield 'true' elif o is False: yield 'false' elif isinstance(o, (int, long)): yield str(o) elif isinstance(o, float): yield _floatstr(o) elif isinstance(o, (list, tuple)): for chunk in _iterencode_list(o, _current_indent_level): yield chunk elif isinstance(o, dict): for chunk in _iterencode_dict(o, _current_indent_level): yield chunk else: if markers is not None: markerid = id(o) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = o o = _default(o) for chunk in _iterencode(o, _current_indent_level): yield chunk if markers is not None: del markers[markerid] return _iterencode
Python
r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format. :mod:`simplejson` exposes an API familiar to users of the standard library :mod:`marshal` and :mod:`pickle` modules. It is the externally maintained version of the :mod:`json` library contained in Python 2.6, but maintains compatibility with Python 2.4 and Python 2.5 and (currently) has significant performance advantages, even without using the optional C extension for speedups. Encoding basic Python object hierarchies:: >>> import simplejson as json >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' >>> print json.dumps("\"foo\bar") "\"foo\bar" >>> print json.dumps(u'\u1234') "\u1234" >>> print json.dumps('\\') "\\" >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) {"a": 0, "b": 0, "c": 0} >>> from StringIO import StringIO >>> io = StringIO() >>> json.dump(['streaming API'], io) >>> io.getvalue() '["streaming API"]' Compact encoding:: >>> import simplejson as json >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':')) '[1,2,3,{"4":5,"6":7}]' Pretty printing:: >>> import simplejson as json >>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) >>> print '\n'.join([l.rstrip() for l in s.splitlines()]) { "4": 5, "6": 7 } Decoding JSON:: >>> import simplejson as json >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj True >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar' True >>> from StringIO import StringIO >>> io = StringIO('["streaming API"]') >>> json.load(io)[0] == 'streaming API' True Specializing JSON object decoding:: >>> import simplejson as json >>> def as_complex(dct): ... if '__complex__' in dct: ... return complex(dct['real'], dct['imag']) ... return dct ... >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', ... object_hook=as_complex) (1+2j) >>> import decimal >>> json.loads('1.1', parse_float=decimal.Decimal) == decimal.Decimal('1.1') True Specializing JSON object encoding:: >>> import simplejson as json >>> def encode_complex(obj): ... if isinstance(obj, complex): ... return [obj.real, obj.imag] ... raise TypeError("%r is not JSON serializable" % (o,)) ... >>> json.dumps(2 + 1j, default=encode_complex) '[2.0, 1.0]' >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j) '[2.0, 1.0]' >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j)) '[2.0, 1.0]' Using simplejson.tool from the shell to validate and pretty-print:: $ echo '{"json":"obj"}' | python -msimplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -msimplejson.tool Expecting property name: line 1 column 2 (char 2) """ __version__ = '2.0.7' __all__ = [ 'dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONEncoder', ] from decoder import JSONDecoder from encoder import JSONEncoder _default_encoder = JSONEncoder( skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, encoding='utf-8', default=None, ) def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, **kw): """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object). If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp`` may be ``unicode`` instances, subject to normal Python ``str`` to ``unicode`` coercion rules. Unless ``fp.write()`` explicitly understands ``unicode`` (as in ``codecs.getwriter()``) this is likely to cause an error. If ``check_circular`` is ``False``, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. ``None`` is the most compact representation. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (skipkeys is False and ensure_ascii is True and check_circular is True and allow_nan is True and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and not kw): iterable = _default_encoder.iterencode(obj) else: if cls is None: cls = JSONEncoder iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, **kw).iterencode(obj) # could accelerate with writelines in some versions of Python, at # a debuggability cost for chunk in iterable: fp.write(chunk) def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, **kw): """Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is ``False``, then the return value will be a ``unicode`` instance subject to normal Python ``str`` to ``unicode`` coercion rules instead of being escaped to an ASCII ``str``. If ``check_circular`` is ``False``, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. ``None`` is the most compact representation. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (skipkeys is False and ensure_ascii is True and check_circular is True and allow_nan is True and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and not kw): return _default_encoder.encode(obj) if cls is None: cls = JSONEncoder return cls( skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, **kw).encode(obj) _default_decoder = JSONDecoder(encoding=None, object_hook=None) def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, **kw): """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. If the contents of ``fp`` is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed, and should be wrapped with ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode`` object and passed to ``loads()`` ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ return loads(fp.read(), encoding=encoding, cls=cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, **kw) def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, **kw): """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) to a Python object. If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to ``unicode`` first. ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN, null, true, false. This can be used to raise an exception if invalid JSON numbers are encountered. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ if (cls is None and encoding is None and object_hook is None and parse_int is None and parse_float is None and parse_constant is None and not kw): return _default_decoder.decode(s) if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook if parse_float is not None: kw['parse_float'] = parse_float if parse_int is not None: kw['parse_int'] = parse_int if parse_constant is not None: kw['parse_constant'] = parse_constant return cls(encoding=encoding, **kw).decode(s)
Python
r"""Using simplejson from the shell to validate and pretty-print:: $ echo '{"json":"obj"}' | python -msimplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -msimplejson.tool Expecting property name: line 1 column 2 (char 2) """ import simplejson def main(): import sys if len(sys.argv) == 1: infile = sys.stdin outfile = sys.stdout elif len(sys.argv) == 2: infile = open(sys.argv[1], 'rb') outfile = sys.stdout elif len(sys.argv) == 3: infile = open(sys.argv[1], 'rb') outfile = open(sys.argv[2], 'wb') else: raise SystemExit("%s [infile [outfile]]" % (sys.argv[0],)) try: obj = simplejson.load(infile) except ValueError, e: raise SystemExit(e) simplejson.dump(obj, outfile, sort_keys=True, indent=4) outfile.write('\n') if __name__ == '__main__': main()
Python
#!/usr/bin/python2.4 # # Copyright 2007 The Python-Twitter Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''A library that provides a Python interface to the Twitter API''' __author__ = 'python-twitter@googlegroups.com' __version__ = '0.8.3' import base64 import calendar import datetime import httplib import os import rfc822 import sys import tempfile import textwrap import time import calendar import urllib import urllib2 import urlparse import gzip import StringIO try: # Python >= 2.6 import json as simplejson except ImportError: try: # Python < 2.6 import simplejson except ImportError: try: # Google App Engine from django.utils import simplejson except ImportError: raise ImportError, "Unable to load a json library" # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl, parse_qs except ImportError: from cgi import parse_qsl, parse_qs try: from hashlib import md5 except ImportError: from md5 import md5 import oauth2 as oauth CHARACTER_LIMIT = 140 # A singleton representing a lazily instantiated FileCache. DEFAULT_CACHE = object() REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' class TwitterError(Exception): '''Base class for Twitter errors''' @property def message(self): '''Returns the first argument used to construct this error.''' return self.args[0] class Status(object): '''A class representing the Status structure used by the twitter API. The Status structure exposes the following properties: status.created_at status.created_at_in_seconds # read only status.favorited status.in_reply_to_screen_name status.in_reply_to_user_id status.in_reply_to_status_id status.truncated status.source status.id status.text status.location status.relative_created_at # read only status.user status.urls status.user_mentions status.hashtags status.geo status.place status.coordinates status.contributors ''' def __init__(self, created_at=None, favorited=None, id=None, text=None, location=None, user=None, in_reply_to_screen_name=None, in_reply_to_user_id=None, in_reply_to_status_id=None, truncated=None, source=None, now=None, urls=None, user_mentions=None, hashtags=None, geo=None, place=None, coordinates=None, contributors=None, retweeted=None, retweeted_status=None, retweet_count=None): '''An object to hold a Twitter status message. This class is normally instantiated by the twitter.Api class and returned in a sequence. Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007" Args: created_at: The time this status message was posted. [Optional] favorited: Whether this is a favorite of the authenticated user. [Optional] id: The unique id of this status message. [Optional] text: The text of this status message. [Optional] location: the geolocation string associated with this message. [Optional] relative_created_at: A human readable string representing the posting time. [Optional] user: A twitter.User instance representing the person posting the message. [Optional] now: The current time, if the client choses to set it. Defaults to the wall clock time. [Optional] urls: user_mentions: hashtags: geo: place: coordinates: contributors: retweeted: retweeted_status: retweet_count: ''' self.created_at = created_at self.favorited = favorited self.id = id self.text = text self.location = location self.user = user self.now = now self.in_reply_to_screen_name = in_reply_to_screen_name self.in_reply_to_user_id = in_reply_to_user_id self.in_reply_to_status_id = in_reply_to_status_id self.truncated = truncated self.retweeted = retweeted self.source = source self.urls = urls self.user_mentions = user_mentions self.hashtags = hashtags self.geo = geo self.place = place self.coordinates = coordinates self.contributors = contributors self.retweeted_status = retweeted_status self.retweet_count = retweet_count def GetCreatedAt(self): '''Get the time this status message was posted. Returns: The time this status message was posted ''' return self._created_at def SetCreatedAt(self, created_at): '''Set the time this status message was posted. Args: created_at: The time this status message was created ''' self._created_at = created_at created_at = property(GetCreatedAt, SetCreatedAt, doc='The time this status message was posted.') def GetCreatedAtInSeconds(self): '''Get the time this status message was posted, in seconds since the epoch. Returns: The time this status message was posted, in seconds since the epoch. ''' return calendar.timegm(rfc822.parsedate(self.created_at)) created_at_in_seconds = property(GetCreatedAtInSeconds, doc="The time this status message was " "posted, in seconds since the epoch") def GetFavorited(self): '''Get the favorited setting of this status message. Returns: True if this status message is favorited; False otherwise ''' return self._favorited def SetFavorited(self, favorited): '''Set the favorited state of this status message. Args: favorited: boolean True/False favorited state of this status message ''' self._favorited = favorited favorited = property(GetFavorited, SetFavorited, doc='The favorited state of this status message.') def GetId(self): '''Get the unique id of this status message. Returns: The unique id of this status message ''' return self._id def SetId(self, id): '''Set the unique id of this status message. Args: id: The unique id of this status message ''' self._id = id id = property(GetId, SetId, doc='The unique id of this status message.') def GetInReplyToScreenName(self): return self._in_reply_to_screen_name def SetInReplyToScreenName(self, in_reply_to_screen_name): self._in_reply_to_screen_name = in_reply_to_screen_name in_reply_to_screen_name = property(GetInReplyToScreenName, SetInReplyToScreenName, doc='') def GetInReplyToUserId(self): return self._in_reply_to_user_id def SetInReplyToUserId(self, in_reply_to_user_id): self._in_reply_to_user_id = in_reply_to_user_id in_reply_to_user_id = property(GetInReplyToUserId, SetInReplyToUserId, doc='') def GetInReplyToStatusId(self): return self._in_reply_to_status_id def SetInReplyToStatusId(self, in_reply_to_status_id): self._in_reply_to_status_id = in_reply_to_status_id in_reply_to_status_id = property(GetInReplyToStatusId, SetInReplyToStatusId, doc='') def GetTruncated(self): return self._truncated def SetTruncated(self, truncated): self._truncated = truncated truncated = property(GetTruncated, SetTruncated, doc='') def GetRetweeted(self): return self._retweeted def SetRetweeted(self, retweeted): self._retweeted = retweeted retweeted = property(GetRetweeted, SetRetweeted, doc='') def GetSource(self): return self._source def SetSource(self, source): self._source = source source = property(GetSource, SetSource, doc='') def GetText(self): '''Get the text of this status message. Returns: The text of this status message. ''' return self._text def SetText(self, text): '''Set the text of this status message. Args: text: The text of this status message ''' self._text = text text = property(GetText, SetText, doc='The text of this status message') def GetLocation(self): '''Get the geolocation associated with this status message Returns: The geolocation string of this status message. ''' return self._location def SetLocation(self, location): '''Set the geolocation associated with this status message Args: location: The geolocation string of this status message ''' self._location = location location = property(GetLocation, SetLocation, doc='The geolocation string of this status message') def GetRelativeCreatedAt(self): '''Get a human redable string representing the posting time Returns: A human readable string representing the posting time ''' fudge = 1.25 delta = long(self.now) - long(self.created_at_in_seconds) if delta < (1 * fudge): return 'about a second ago' elif delta < (60 * (1/fudge)): return 'about %d seconds ago' % (delta) elif delta < (60 * fudge): return 'about a minute ago' elif delta < (60 * 60 * (1/fudge)): return 'about %d minutes ago' % (delta / 60) elif delta < (60 * 60 * fudge) or delta / (60 * 60) == 1: return 'about an hour ago' elif delta < (60 * 60 * 24 * (1/fudge)): return 'about %d hours ago' % (delta / (60 * 60)) elif delta < (60 * 60 * 24 * fudge) or delta / (60 * 60 * 24) == 1: return 'about a day ago' else: return 'about %d days ago' % (delta / (60 * 60 * 24)) relative_created_at = property(GetRelativeCreatedAt, doc='Get a human readable string representing ' 'the posting time') def GetUser(self): '''Get a twitter.User reprenting the entity posting this status message. Returns: A twitter.User reprenting the entity posting this status message ''' return self._user def SetUser(self, user): '''Set a twitter.User reprenting the entity posting this status message. Args: user: A twitter.User reprenting the entity posting this status message ''' self._user = user user = property(GetUser, SetUser, doc='A twitter.User reprenting the entity posting this ' 'status message') def GetNow(self): '''Get the wallclock time for this status message. Used to calculate relative_created_at. Defaults to the time the object was instantiated. Returns: Whatever the status instance believes the current time to be, in seconds since the epoch. ''' if self._now is None: self._now = time.time() return self._now def SetNow(self, now): '''Set the wallclock time for this status message. Used to calculate relative_created_at. Defaults to the time the object was instantiated. Args: now: The wallclock time for this instance. ''' self._now = now now = property(GetNow, SetNow, doc='The wallclock time for this status instance.') def GetGeo(self): return self._geo def SetGeo(self, geo): self._geo = geo geo = property(GetGeo, SetGeo, doc='') def GetPlace(self): return self._place def SetPlace(self, place): self._place = place place = property(GetPlace, SetPlace, doc='') def GetCoordinates(self): return self._coordinates def SetCoordinates(self, coordinates): self._coordinates = coordinates coordinates = property(GetCoordinates, SetCoordinates, doc='') def GetContributors(self): return self._contributors def SetContributors(self, contributors): self._contributors = contributors contributors = property(GetContributors, SetContributors, doc='') def GetRetweeted_status(self): return self._retweeted_status def SetRetweeted_status(self, retweeted_status): self._retweeted_status = retweeted_status retweeted_status = property(GetRetweeted_status, SetRetweeted_status, doc='') def GetRetweetCount(self): return self._retweet_count def SetRetweetCount(self, retweet_count): self._retweet_count = retweet_count retweet_count = property(GetRetweetCount, SetRetweetCount, doc='') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.created_at == other.created_at and \ self.id == other.id and \ self.text == other.text and \ self.location == other.location and \ self.user == other.user and \ self.in_reply_to_screen_name == other.in_reply_to_screen_name and \ self.in_reply_to_user_id == other.in_reply_to_user_id and \ self.in_reply_to_status_id == other.in_reply_to_status_id and \ self.truncated == other.truncated and \ self.retweeted == other.retweeted and \ self.favorited == other.favorited and \ self.source == other.source and \ self.geo == other.geo and \ self.place == other.place and \ self.coordinates == other.coordinates and \ self.contributors == other.contributors and \ self.retweeted_status == other.retweeted_status and \ self.retweet_count == other.retweet_count except AttributeError: return False def __str__(self): '''A string representation of this twitter.Status instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.Status instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.Status instance. Returns: A JSON string representation of this twitter.Status instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.Status instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.Status instance ''' data = {} if self.created_at: data['created_at'] = self.created_at if self.favorited: data['favorited'] = self.favorited if self.id: data['id'] = self.id if self.text: data['text'] = self.text if self.location: data['location'] = self.location if self.user: data['user'] = self.user.AsDict() if self.in_reply_to_screen_name: data['in_reply_to_screen_name'] = self.in_reply_to_screen_name if self.in_reply_to_user_id: data['in_reply_to_user_id'] = self.in_reply_to_user_id if self.in_reply_to_status_id: data['in_reply_to_status_id'] = self.in_reply_to_status_id if self.truncated is not None: data['truncated'] = self.truncated if self.retweeted is not None: data['retweeted'] = self.retweeted if self.favorited is not None: data['favorited'] = self.favorited if self.source: data['source'] = self.source if self.geo: data['geo'] = self.geo if self.place: data['place'] = self.place if self.coordinates: data['coordinates'] = self.coordinates if self.contributors: data['contributors'] = self.contributors if self.hashtags: data['hashtags'] = [h.text for h in self.hashtags] if self.retweeted_status: data['retweeted_status'] = self.retweeted_status.AsDict() if self.retweet_count: data['retweet_count'] = self.retweet_count if self.urls: data['urls'] = dict([(url.url, url.expanded_url) for url in self.urls]) if self.user_mentions: data['user_mentions'] = [um.AsDict() for um in self.user_mentions] return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.Status instance ''' if 'user' in data: user = User.NewFromJsonDict(data['user']) else: user = None if 'retweeted_status' in data: retweeted_status = Status.NewFromJsonDict(data['retweeted_status']) else: retweeted_status = None urls = None user_mentions = None hashtags = None if 'entities' in data: if 'urls' in data['entities']: urls = [Url.NewFromJsonDict(u) for u in data['entities']['urls']] if 'user_mentions' in data['entities']: user_mentions = [User.NewFromJsonDict(u) for u in data['entities']['user_mentions']] if 'hashtags' in data['entities']: hashtags = [Hashtag.NewFromJsonDict(h) for h in data['entities']['hashtags']] return Status(created_at=data.get('created_at', None), favorited=data.get('favorited', None), id=data.get('id', None), text=data.get('text', None), location=data.get('location', None), in_reply_to_screen_name=data.get('in_reply_to_screen_name', None), in_reply_to_user_id=data.get('in_reply_to_user_id', None), in_reply_to_status_id=data.get('in_reply_to_status_id', None), truncated=data.get('truncated', None), retweeted=data.get('retweeted', None), source=data.get('source', None), user=user, urls=urls, user_mentions=user_mentions, hashtags=hashtags, geo=data.get('geo', None), place=data.get('place', None), coordinates=data.get('coordinates', None), contributors=data.get('contributors', None), retweeted_status=retweeted_status, retweet_count=data.get('retweet_count', None)) class User(object): '''A class representing the User structure used by the twitter API. The User structure exposes the following properties: user.id user.name user.screen_name user.location user.description user.profile_image_url user.profile_background_tile user.profile_background_image_url user.profile_sidebar_fill_color user.profile_background_color user.profile_link_color user.profile_text_color user.protected user.utc_offset user.time_zone user.url user.status user.statuses_count user.followers_count user.friends_count user.favourites_count user.geo_enabled user.verified user.lang user.notifications user.contributors_enabled user.created_at user.listed_count ''' def __init__(self, id=None, name=None, screen_name=None, location=None, description=None, profile_image_url=None, profile_background_tile=None, profile_background_image_url=None, profile_sidebar_fill_color=None, profile_background_color=None, profile_link_color=None, profile_text_color=None, protected=None, utc_offset=None, time_zone=None, followers_count=None, friends_count=None, statuses_count=None, favourites_count=None, url=None, status=None, geo_enabled=None, verified=None, lang=None, notifications=None, contributors_enabled=None, created_at=None, listed_count=None): self.id = id self.name = name self.screen_name = screen_name self.location = location self.description = description self.profile_image_url = profile_image_url self.profile_background_tile = profile_background_tile self.profile_background_image_url = profile_background_image_url self.profile_sidebar_fill_color = profile_sidebar_fill_color self.profile_background_color = profile_background_color self.profile_link_color = profile_link_color self.profile_text_color = profile_text_color self.protected = protected self.utc_offset = utc_offset self.time_zone = time_zone self.followers_count = followers_count self.friends_count = friends_count self.statuses_count = statuses_count self.favourites_count = favourites_count self.url = url self.status = status self.geo_enabled = geo_enabled self.verified = verified self.lang = lang self.notifications = notifications self.contributors_enabled = contributors_enabled self.created_at = created_at self.listed_count = listed_count def GetId(self): '''Get the unique id of this user. Returns: The unique id of this user ''' return self._id def SetId(self, id): '''Set the unique id of this user. Args: id: The unique id of this user. ''' self._id = id id = property(GetId, SetId, doc='The unique id of this user.') def GetName(self): '''Get the real name of this user. Returns: The real name of this user ''' return self._name def SetName(self, name): '''Set the real name of this user. Args: name: The real name of this user ''' self._name = name name = property(GetName, SetName, doc='The real name of this user.') def GetScreenName(self): '''Get the short twitter name of this user. Returns: The short twitter name of this user ''' return self._screen_name def SetScreenName(self, screen_name): '''Set the short twitter name of this user. Args: screen_name: the short twitter name of this user ''' self._screen_name = screen_name screen_name = property(GetScreenName, SetScreenName, doc='The short twitter name of this user.') def GetLocation(self): '''Get the geographic location of this user. Returns: The geographic location of this user ''' return self._location def SetLocation(self, location): '''Set the geographic location of this user. Args: location: The geographic location of this user ''' self._location = location location = property(GetLocation, SetLocation, doc='The geographic location of this user.') def GetDescription(self): '''Get the short text description of this user. Returns: The short text description of this user ''' return self._description def SetDescription(self, description): '''Set the short text description of this user. Args: description: The short text description of this user ''' self._description = description description = property(GetDescription, SetDescription, doc='The short text description of this user.') def GetUrl(self): '''Get the homepage url of this user. Returns: The homepage url of this user ''' return self._url def SetUrl(self, url): '''Set the homepage url of this user. Args: url: The homepage url of this user ''' self._url = url url = property(GetUrl, SetUrl, doc='The homepage url of this user.') def GetProfileImageUrl(self): '''Get the url of the thumbnail of this user. Returns: The url of the thumbnail of this user ''' return self._profile_image_url def SetProfileImageUrl(self, profile_image_url): '''Set the url of the thumbnail of this user. Args: profile_image_url: The url of the thumbnail of this user ''' self._profile_image_url = profile_image_url profile_image_url= property(GetProfileImageUrl, SetProfileImageUrl, doc='The url of the thumbnail of this user.') def GetProfileBackgroundTile(self): '''Boolean for whether to tile the profile background image. Returns: True if the background is to be tiled, False if not, None if unset. ''' return self._profile_background_tile def SetProfileBackgroundTile(self, profile_background_tile): '''Set the boolean flag for whether to tile the profile background image. Args: profile_background_tile: Boolean flag for whether to tile or not. ''' self._profile_background_tile = profile_background_tile profile_background_tile = property(GetProfileBackgroundTile, SetProfileBackgroundTile, doc='Boolean for whether to tile the background image.') def GetProfileBackgroundImageUrl(self): return self._profile_background_image_url def SetProfileBackgroundImageUrl(self, profile_background_image_url): self._profile_background_image_url = profile_background_image_url profile_background_image_url = property(GetProfileBackgroundImageUrl, SetProfileBackgroundImageUrl, doc='The url of the profile background of this user.') def GetProfileSidebarFillColor(self): return self._profile_sidebar_fill_color def SetProfileSidebarFillColor(self, profile_sidebar_fill_color): self._profile_sidebar_fill_color = profile_sidebar_fill_color profile_sidebar_fill_color = property(GetProfileSidebarFillColor, SetProfileSidebarFillColor) def GetProfileBackgroundColor(self): return self._profile_background_color def SetProfileBackgroundColor(self, profile_background_color): self._profile_background_color = profile_background_color profile_background_color = property(GetProfileBackgroundColor, SetProfileBackgroundColor) def GetProfileLinkColor(self): return self._profile_link_color def SetProfileLinkColor(self, profile_link_color): self._profile_link_color = profile_link_color profile_link_color = property(GetProfileLinkColor, SetProfileLinkColor) def GetProfileTextColor(self): return self._profile_text_color def SetProfileTextColor(self, profile_text_color): self._profile_text_color = profile_text_color profile_text_color = property(GetProfileTextColor, SetProfileTextColor) def GetProtected(self): return self._protected def SetProtected(self, protected): self._protected = protected protected = property(GetProtected, SetProtected) def GetUtcOffset(self): return self._utc_offset def SetUtcOffset(self, utc_offset): self._utc_offset = utc_offset utc_offset = property(GetUtcOffset, SetUtcOffset) def GetTimeZone(self): '''Returns the current time zone string for the user. Returns: The descriptive time zone string for the user. ''' return self._time_zone def SetTimeZone(self, time_zone): '''Sets the user's time zone string. Args: time_zone: The descriptive time zone to assign for the user. ''' self._time_zone = time_zone time_zone = property(GetTimeZone, SetTimeZone) def GetStatus(self): '''Get the latest twitter.Status of this user. Returns: The latest twitter.Status of this user ''' return self._status def SetStatus(self, status): '''Set the latest twitter.Status of this user. Args: status: The latest twitter.Status of this user ''' self._status = status status = property(GetStatus, SetStatus, doc='The latest twitter.Status of this user.') def GetFriendsCount(self): '''Get the friend count for this user. Returns: The number of users this user has befriended. ''' return self._friends_count def SetFriendsCount(self, count): '''Set the friend count for this user. Args: count: The number of users this user has befriended. ''' self._friends_count = count friends_count = property(GetFriendsCount, SetFriendsCount, doc='The number of friends for this user.') def GetListedCount(self): '''Get the listed count for this user. Returns: The number of lists this user belongs to. ''' return self._listed_count def SetListedCount(self, count): '''Set the listed count for this user. Args: count: The number of lists this user belongs to. ''' self._listed_count = count listed_count = property(GetListedCount, SetListedCount, doc='The number of lists this user belongs to.') def GetFollowersCount(self): '''Get the follower count for this user. Returns: The number of users following this user. ''' return self._followers_count def SetFollowersCount(self, count): '''Set the follower count for this user. Args: count: The number of users following this user. ''' self._followers_count = count followers_count = property(GetFollowersCount, SetFollowersCount, doc='The number of users following this user.') def GetStatusesCount(self): '''Get the number of status updates for this user. Returns: The number of status updates for this user. ''' return self._statuses_count def SetStatusesCount(self, count): '''Set the status update count for this user. Args: count: The number of updates for this user. ''' self._statuses_count = count statuses_count = property(GetStatusesCount, SetStatusesCount, doc='The number of updates for this user.') def GetFavouritesCount(self): '''Get the number of favourites for this user. Returns: The number of favourites for this user. ''' return self._favourites_count def SetFavouritesCount(self, count): '''Set the favourite count for this user. Args: count: The number of favourites for this user. ''' self._favourites_count = count favourites_count = property(GetFavouritesCount, SetFavouritesCount, doc='The number of favourites for this user.') def GetGeoEnabled(self): '''Get the setting of geo_enabled for this user. Returns: True/False if Geo tagging is enabled ''' return self._geo_enabled def SetGeoEnabled(self, geo_enabled): '''Set the latest twitter.geo_enabled of this user. Args: geo_enabled: True/False if Geo tagging is to be enabled ''' self._geo_enabled = geo_enabled geo_enabled = property(GetGeoEnabled, SetGeoEnabled, doc='The value of twitter.geo_enabled for this user.') def GetVerified(self): '''Get the setting of verified for this user. Returns: True/False if user is a verified account ''' return self._verified def SetVerified(self, verified): '''Set twitter.verified for this user. Args: verified: True/False if user is a verified account ''' self._verified = verified verified = property(GetVerified, SetVerified, doc='The value of twitter.verified for this user.') def GetLang(self): '''Get the setting of lang for this user. Returns: language code of the user ''' return self._lang def SetLang(self, lang): '''Set twitter.lang for this user. Args: lang: language code for the user ''' self._lang = lang lang = property(GetLang, SetLang, doc='The value of twitter.lang for this user.') def GetNotifications(self): '''Get the setting of notifications for this user. Returns: True/False for the notifications setting of the user ''' return self._notifications def SetNotifications(self, notifications): '''Set twitter.notifications for this user. Args: notifications: True/False notifications setting for the user ''' self._notifications = notifications notifications = property(GetNotifications, SetNotifications, doc='The value of twitter.notifications for this user.') def GetContributorsEnabled(self): '''Get the setting of contributors_enabled for this user. Returns: True/False contributors_enabled of the user ''' return self._contributors_enabled def SetContributorsEnabled(self, contributors_enabled): '''Set twitter.contributors_enabled for this user. Args: contributors_enabled: True/False contributors_enabled setting for the user ''' self._contributors_enabled = contributors_enabled contributors_enabled = property(GetContributorsEnabled, SetContributorsEnabled, doc='The value of twitter.contributors_enabled for this user.') def GetCreatedAt(self): '''Get the setting of created_at for this user. Returns: created_at value of the user ''' return self._created_at def SetCreatedAt(self, created_at): '''Set twitter.created_at for this user. Args: created_at: created_at value for the user ''' self._created_at = created_at created_at = property(GetCreatedAt, SetCreatedAt, doc='The value of twitter.created_at for this user.') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.id == other.id and \ self.name == other.name and \ self.screen_name == other.screen_name and \ self.location == other.location and \ self.description == other.description and \ self.profile_image_url == other.profile_image_url and \ self.profile_background_tile == other.profile_background_tile and \ self.profile_background_image_url == other.profile_background_image_url and \ self.profile_sidebar_fill_color == other.profile_sidebar_fill_color and \ self.profile_background_color == other.profile_background_color and \ self.profile_link_color == other.profile_link_color and \ self.profile_text_color == other.profile_text_color and \ self.protected == other.protected and \ self.utc_offset == other.utc_offset and \ self.time_zone == other.time_zone and \ self.url == other.url and \ self.statuses_count == other.statuses_count and \ self.followers_count == other.followers_count and \ self.favourites_count == other.favourites_count and \ self.friends_count == other.friends_count and \ self.status == other.status and \ self.geo_enabled == other.geo_enabled and \ self.verified == other.verified and \ self.lang == other.lang and \ self.notifications == other.notifications and \ self.contributors_enabled == other.contributors_enabled and \ self.created_at == other.created_at and \ self.listed_count == other.listed_count except AttributeError: return False def __str__(self): '''A string representation of this twitter.User instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.User instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.User instance. Returns: A JSON string representation of this twitter.User instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.User instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.User instance ''' data = {} if self.id: data['id'] = self.id if self.name: data['name'] = self.name if self.screen_name: data['screen_name'] = self.screen_name if self.location: data['location'] = self.location if self.description: data['description'] = self.description if self.profile_image_url: data['profile_image_url'] = self.profile_image_url if self.profile_background_tile is not None: data['profile_background_tile'] = self.profile_background_tile if self.profile_background_image_url: data['profile_sidebar_fill_color'] = self.profile_background_image_url if self.profile_background_color: data['profile_background_color'] = self.profile_background_color if self.profile_link_color: data['profile_link_color'] = self.profile_link_color if self.profile_text_color: data['profile_text_color'] = self.profile_text_color if self.protected is not None: data['protected'] = self.protected if self.utc_offset: data['utc_offset'] = self.utc_offset if self.time_zone: data['time_zone'] = self.time_zone if self.url: data['url'] = self.url if self.status: data['status'] = self.status.AsDict() if self.friends_count: data['friends_count'] = self.friends_count if self.followers_count: data['followers_count'] = self.followers_count if self.statuses_count: data['statuses_count'] = self.statuses_count if self.favourites_count: data['favourites_count'] = self.favourites_count if self.geo_enabled: data['geo_enabled'] = self.geo_enabled if self.verified: data['verified'] = self.verified if self.lang: data['lang'] = self.lang if self.notifications: data['notifications'] = self.notifications if self.contributors_enabled: data['contributors_enabled'] = self.contributors_enabled if self.created_at: data['created_at'] = self.created_at if self.listed_count: data['listed_count'] = self.listed_count return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.User instance ''' if 'status' in data: status = Status.NewFromJsonDict(data['status']) else: status = None return User(id=data.get('id', None), name=data.get('name', None), screen_name=data.get('screen_name', None), location=data.get('location', None), description=data.get('description', None), statuses_count=data.get('statuses_count', None), followers_count=data.get('followers_count', None), favourites_count=data.get('favourites_count', None), friends_count=data.get('friends_count', None), profile_image_url=data.get('profile_image_url', None), profile_background_tile = data.get('profile_background_tile', None), profile_background_image_url = data.get('profile_background_image_url', None), profile_sidebar_fill_color = data.get('profile_sidebar_fill_color', None), profile_background_color = data.get('profile_background_color', None), profile_link_color = data.get('profile_link_color', None), profile_text_color = data.get('profile_text_color', None), protected = data.get('protected', None), utc_offset = data.get('utc_offset', None), time_zone = data.get('time_zone', None), url=data.get('url', None), status=status, geo_enabled=data.get('geo_enabled', None), verified=data.get('verified', None), lang=data.get('lang', None), notifications=data.get('notifications', None), contributors_enabled=data.get('contributors_enabled', None), created_at=data.get('created_at', None), listed_count=data.get('listed_count', None)) class List(object): '''A class representing the List structure used by the twitter API. The List structure exposes the following properties: list.id list.name list.slug list.description list.full_name list.mode list.uri list.member_count list.subscriber_count list.following ''' def __init__(self, id=None, name=None, slug=None, description=None, full_name=None, mode=None, uri=None, member_count=None, subscriber_count=None, following=None, user=None): self.id = id self.name = name self.slug = slug self.description = description self.full_name = full_name self.mode = mode self.uri = uri self.member_count = member_count self.subscriber_count = subscriber_count self.following = following self.user = user def GetId(self): '''Get the unique id of this list. Returns: The unique id of this list ''' return self._id def SetId(self, id): '''Set the unique id of this list. Args: id: The unique id of this list. ''' self._id = id id = property(GetId, SetId, doc='The unique id of this list.') def GetName(self): '''Get the real name of this list. Returns: The real name of this list ''' return self._name def SetName(self, name): '''Set the real name of this list. Args: name: The real name of this list ''' self._name = name name = property(GetName, SetName, doc='The real name of this list.') def GetSlug(self): '''Get the slug of this list. Returns: The slug of this list ''' return self._slug def SetSlug(self, slug): '''Set the slug of this list. Args: slug: The slug of this list. ''' self._slug = slug slug = property(GetSlug, SetSlug, doc='The slug of this list.') def GetDescription(self): '''Get the description of this list. Returns: The description of this list ''' return self._description def SetDescription(self, description): '''Set the description of this list. Args: description: The description of this list. ''' self._description = description description = property(GetDescription, SetDescription, doc='The description of this list.') def GetFull_name(self): '''Get the full_name of this list. Returns: The full_name of this list ''' return self._full_name def SetFull_name(self, full_name): '''Set the full_name of this list. Args: full_name: The full_name of this list. ''' self._full_name = full_name full_name = property(GetFull_name, SetFull_name, doc='The full_name of this list.') def GetMode(self): '''Get the mode of this list. Returns: The mode of this list ''' return self._mode def SetMode(self, mode): '''Set the mode of this list. Args: mode: The mode of this list. ''' self._mode = mode mode = property(GetMode, SetMode, doc='The mode of this list.') def GetUri(self): '''Get the uri of this list. Returns: The uri of this list ''' return self._uri def SetUri(self, uri): '''Set the uri of this list. Args: uri: The uri of this list. ''' self._uri = uri uri = property(GetUri, SetUri, doc='The uri of this list.') def GetMember_count(self): '''Get the member_count of this list. Returns: The member_count of this list ''' return self._member_count def SetMember_count(self, member_count): '''Set the member_count of this list. Args: member_count: The member_count of this list. ''' self._member_count = member_count member_count = property(GetMember_count, SetMember_count, doc='The member_count of this list.') def GetSubscriber_count(self): '''Get the subscriber_count of this list. Returns: The subscriber_count of this list ''' return self._subscriber_count def SetSubscriber_count(self, subscriber_count): '''Set the subscriber_count of this list. Args: subscriber_count: The subscriber_count of this list. ''' self._subscriber_count = subscriber_count subscriber_count = property(GetSubscriber_count, SetSubscriber_count, doc='The subscriber_count of this list.') def GetFollowing(self): '''Get the following status of this list. Returns: The following status of this list ''' return self._following def SetFollowing(self, following): '''Set the following status of this list. Args: following: The following of this list. ''' self._following = following following = property(GetFollowing, SetFollowing, doc='The following status of this list.') def GetUser(self): '''Get the user of this list. Returns: The owner of this list ''' return self._user def SetUser(self, user): '''Set the user of this list. Args: user: The owner of this list. ''' self._user = user user = property(GetUser, SetUser, doc='The owner of this list.') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.id == other.id and \ self.name == other.name and \ self.slug == other.slug and \ self.description == other.description and \ self.full_name == other.full_name and \ self.mode == other.mode and \ self.uri == other.uri and \ self.member_count == other.member_count and \ self.subscriber_count == other.subscriber_count and \ self.following == other.following and \ self.user == other.user except AttributeError: return False def __str__(self): '''A string representation of this twitter.List instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.List instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.List instance. Returns: A JSON string representation of this twitter.List instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.List instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.List instance ''' data = {} if self.id: data['id'] = self.id if self.name: data['name'] = self.name if self.slug: data['slug'] = self.slug if self.description: data['description'] = self.description if self.full_name: data['full_name'] = self.full_name if self.mode: data['mode'] = self.mode if self.uri: data['uri'] = self.uri if self.member_count is not None: data['member_count'] = self.member_count if self.subscriber_count is not None: data['subscriber_count'] = self.subscriber_count if self.following is not None: data['following'] = self.following if self.user is not None: data['user'] = self.user return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.List instance ''' if 'user' in data: user = User.NewFromJsonDict(data['user']) else: user = None return List(id=data.get('id', None), name=data.get('name', None), slug=data.get('slug', None), description=data.get('description', None), full_name=data.get('full_name', None), mode=data.get('mode', None), uri=data.get('uri', None), member_count=data.get('member_count', None), subscriber_count=data.get('subscriber_count', None), following=data.get('following', None), user=user) class DirectMessage(object): '''A class representing the DirectMessage structure used by the twitter API. The DirectMessage structure exposes the following properties: direct_message.id direct_message.created_at direct_message.created_at_in_seconds # read only direct_message.sender_id direct_message.sender_screen_name direct_message.recipient_id direct_message.recipient_screen_name direct_message.text ''' def __init__(self, id=None, created_at=None, sender_id=None, sender_screen_name=None, recipient_id=None, recipient_screen_name=None, text=None): '''An object to hold a Twitter direct message. This class is normally instantiated by the twitter.Api class and returned in a sequence. Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007" Args: id: The unique id of this direct message. [Optional] created_at: The time this direct message was posted. [Optional] sender_id: The id of the twitter user that sent this message. [Optional] sender_screen_name: The name of the twitter user that sent this message. [Optional] recipient_id: The id of the twitter that received this message. [Optional] recipient_screen_name: The name of the twitter that received this message. [Optional] text: The text of this direct message. [Optional] ''' self.id = id self.created_at = created_at self.sender_id = sender_id self.sender_screen_name = sender_screen_name self.recipient_id = recipient_id self.recipient_screen_name = recipient_screen_name self.text = text def GetId(self): '''Get the unique id of this direct message. Returns: The unique id of this direct message ''' return self._id def SetId(self, id): '''Set the unique id of this direct message. Args: id: The unique id of this direct message ''' self._id = id id = property(GetId, SetId, doc='The unique id of this direct message.') def GetCreatedAt(self): '''Get the time this direct message was posted. Returns: The time this direct message was posted ''' return self._created_at def SetCreatedAt(self, created_at): '''Set the time this direct message was posted. Args: created_at: The time this direct message was created ''' self._created_at = created_at created_at = property(GetCreatedAt, SetCreatedAt, doc='The time this direct message was posted.') def GetCreatedAtInSeconds(self): '''Get the time this direct message was posted, in seconds since the epoch. Returns: The time this direct message was posted, in seconds since the epoch. ''' return calendar.timegm(rfc822.parsedate(self.created_at)) created_at_in_seconds = property(GetCreatedAtInSeconds, doc="The time this direct message was " "posted, in seconds since the epoch") def GetSenderId(self): '''Get the unique sender id of this direct message. Returns: The unique sender id of this direct message ''' return self._sender_id def SetSenderId(self, sender_id): '''Set the unique sender id of this direct message. Args: sender_id: The unique sender id of this direct message ''' self._sender_id = sender_id sender_id = property(GetSenderId, SetSenderId, doc='The unique sender id of this direct message.') def GetSenderScreenName(self): '''Get the unique sender screen name of this direct message. Returns: The unique sender screen name of this direct message ''' return self._sender_screen_name def SetSenderScreenName(self, sender_screen_name): '''Set the unique sender screen name of this direct message. Args: sender_screen_name: The unique sender screen name of this direct message ''' self._sender_screen_name = sender_screen_name sender_screen_name = property(GetSenderScreenName, SetSenderScreenName, doc='The unique sender screen name of this direct message.') def GetRecipientId(self): '''Get the unique recipient id of this direct message. Returns: The unique recipient id of this direct message ''' return self._recipient_id def SetRecipientId(self, recipient_id): '''Set the unique recipient id of this direct message. Args: recipient_id: The unique recipient id of this direct message ''' self._recipient_id = recipient_id recipient_id = property(GetRecipientId, SetRecipientId, doc='The unique recipient id of this direct message.') def GetRecipientScreenName(self): '''Get the unique recipient screen name of this direct message. Returns: The unique recipient screen name of this direct message ''' return self._recipient_screen_name def SetRecipientScreenName(self, recipient_screen_name): '''Set the unique recipient screen name of this direct message. Args: recipient_screen_name: The unique recipient screen name of this direct message ''' self._recipient_screen_name = recipient_screen_name recipient_screen_name = property(GetRecipientScreenName, SetRecipientScreenName, doc='The unique recipient screen name of this direct message.') def GetText(self): '''Get the text of this direct message. Returns: The text of this direct message. ''' return self._text def SetText(self, text): '''Set the text of this direct message. Args: text: The text of this direct message ''' self._text = text text = property(GetText, SetText, doc='The text of this direct message') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.id == other.id and \ self.created_at == other.created_at and \ self.sender_id == other.sender_id and \ self.sender_screen_name == other.sender_screen_name and \ self.recipient_id == other.recipient_id and \ self.recipient_screen_name == other.recipient_screen_name and \ self.text == other.text except AttributeError: return False def __str__(self): '''A string representation of this twitter.DirectMessage instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.DirectMessage instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.DirectMessage instance. Returns: A JSON string representation of this twitter.DirectMessage instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.DirectMessage instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.DirectMessage instance ''' data = {} if self.id: data['id'] = self.id if self.created_at: data['created_at'] = self.created_at if self.sender_id: data['sender_id'] = self.sender_id if self.sender_screen_name: data['sender_screen_name'] = self.sender_screen_name if self.recipient_id: data['recipient_id'] = self.recipient_id if self.recipient_screen_name: data['recipient_screen_name'] = self.recipient_screen_name if self.text: data['text'] = self.text return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.DirectMessage instance ''' return DirectMessage(created_at=data.get('created_at', None), recipient_id=data.get('recipient_id', None), sender_id=data.get('sender_id', None), text=data.get('text', None), sender_screen_name=data.get('sender_screen_name', None), id=data.get('id', None), recipient_screen_name=data.get('recipient_screen_name', None)) class Hashtag(object): ''' A class represeinting a twitter hashtag ''' def __init__(self, text=None): self.text = text @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.Hashtag instance ''' return Hashtag(text = data.get('text', None)) class Trend(object): ''' A class representing a trending topic ''' def __init__(self, name=None, query=None, timestamp=None): self.name = name self.query = query self.timestamp = timestamp def __str__(self): return 'Name: %s\nQuery: %s\nTimestamp: %s\n' % (self.name, self.query, self.timestamp) def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.name == other.name and \ self.query == other.query and \ self.timestamp == other.timestamp except AttributeError: return False @staticmethod def NewFromJsonDict(data, timestamp = None): '''Create a new instance based on a JSON dict Args: data: A JSON dict timestamp: Gets set as the timestamp property of the new object Returns: A twitter.Trend object ''' return Trend(name=data.get('name', None), query=data.get('query', None), timestamp=timestamp) class Url(object): '''A class representing an URL contained in a tweet''' def __init__(self, url=None, expanded_url=None): self.url = url self.expanded_url = expanded_url @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.Url instance ''' return Url(url=data.get('url', None), expanded_url=data.get('expanded_url', None)) class Api(object): '''A python interface into the Twitter API By default, the Api caches results for 1 minute. Example usage: To create an instance of the twitter.Api class, with no authentication: >>> import twitter >>> api = twitter.Api() To fetch the most recently posted public twitter status messages: >>> statuses = api.GetPublicTimeline() >>> print [s.user.name for s in statuses] [u'DeWitt', u'Kesuke Miyagi', u'ev', u'Buzz Andersen', u'Biz Stone'] #... To fetch a single user's public status messages, where "user" is either a Twitter "short name" or their user id. >>> statuses = api.GetUserTimeline(user) >>> print [s.text for s in statuses] To use authentication, instantiate the twitter.Api class with a consumer key and secret; and the oAuth key and secret: >>> api = twitter.Api(consumer_key='twitter consumer key', consumer_secret='twitter consumer secret', access_token_key='the_key_given', access_token_secret='the_key_secret') To fetch your friends (after being authenticated): >>> users = api.GetFriends() >>> print [u.name for u in users] To post a twitter status message (after being authenticated): >>> status = api.PostUpdate('I love python-twitter!') >>> print status.text I love python-twitter! There are many other methods, including: >>> api.PostUpdates(status) >>> api.PostDirectMessage(user, text) >>> api.GetUser(user) >>> api.GetReplies() >>> api.GetUserTimeline(user) >>> api.GetStatus(id) >>> api.DestroyStatus(id) >>> api.GetFriendsTimeline(user) >>> api.GetFriends(user) >>> api.GetFollowers() >>> api.GetFeatured() >>> api.GetDirectMessages() >>> api.PostDirectMessage(user, text) >>> api.DestroyDirectMessage(id) >>> api.DestroyFriendship(user) >>> api.CreateFriendship(user) >>> api.GetUserByEmail(email) >>> api.VerifyCredentials() ''' DEFAULT_CACHE_TIMEOUT = 60 # cache for 1 minute _API_REALM = 'Twitter API' def __init__(self, consumer_key=None, consumer_secret=None, access_token_key=None, access_token_secret=None, input_encoding=None, request_headers=None, cache=DEFAULT_CACHE, shortner=None, base_url=None, use_gzip_compression=False, debugHTTP=False): '''Instantiate a new twitter.Api object. Args: consumer_key: Your Twitter user's consumer_key. consumer_secret: Your Twitter user's consumer_secret. access_token_key: The oAuth access token key value you retrieved from running get_access_token.py. access_token_secret: The oAuth access token's secret, also retrieved from the get_access_token.py run. input_encoding: The encoding used to encode input strings. [Optional] request_header: A dictionary of additional HTTP request headers. [Optional] cache: The cache instance to use. Defaults to DEFAULT_CACHE. Use None to disable caching. [Optional] shortner: The shortner instance to use. Defaults to None. See shorten_url.py for an example shortner. [Optional] base_url: The base URL to use to contact the Twitter API. Defaults to https://api.twitter.com. [Optional] use_gzip_compression: Set to True to tell enable gzip compression for any call made to Twitter. Defaults to False. [Optional] debugHTTP: Set to True to enable debug output from urllib2 when performing any HTTP requests. Defaults to False. [Optional] ''' self.SetCache(cache) self._urllib = urllib2 self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT self._input_encoding = input_encoding self._use_gzip = use_gzip_compression self._debugHTTP = debugHTTP self._oauth_consumer = None self._shortlink_size = 19 self._InitializeRequestHeaders(request_headers) self._InitializeUserAgent() self._InitializeDefaultParameters() if base_url is None: self.base_url = 'https://api.twitter.com/1' else: self.base_url = base_url if consumer_key is not None and (access_token_key is None or access_token_secret is None): print >> sys.stderr, 'Twitter now requires an oAuth Access Token for API calls.' print >> sys.stderr, 'If your using this library from a command line utility, please' print >> sys.stderr, 'run the the included get_access_token.py tool to generate one.' raise TwitterError('Twitter requires oAuth Access Token for all API access') self.SetCredentials(consumer_key, consumer_secret, access_token_key, access_token_secret) def SetCredentials(self, consumer_key, consumer_secret, access_token_key=None, access_token_secret=None): '''Set the consumer_key and consumer_secret for this instance Args: consumer_key: The consumer_key of the twitter account. consumer_secret: The consumer_secret for the twitter account. access_token_key: The oAuth access token key value you retrieved from running get_access_token.py. access_token_secret: The oAuth access token's secret, also retrieved from the get_access_token.py run. ''' self._consumer_key = consumer_key self._consumer_secret = consumer_secret self._access_token_key = access_token_key self._access_token_secret = access_token_secret self._oauth_consumer = None if consumer_key is not None and consumer_secret is not None and \ access_token_key is not None and access_token_secret is not None: self._signature_method_plaintext = oauth.SignatureMethod_PLAINTEXT() self._signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() self._oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret) self._oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) def ClearCredentials(self): '''Clear the any credentials for this instance ''' self._consumer_key = None self._consumer_secret = None self._access_token_key = None self._access_token_secret = None self._oauth_consumer = None def GetPublicTimeline(self, since_id=None, include_rts=None, include_entities=None): '''Fetch the sequence of public twitter.Status message for all users. Args: since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] include_rts: If True, the timeline will contain native retweets (if they exist) in addition to the standard stream of tweets. [Optional] include_entities: If True, each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. [Optional] Returns: An sequence of twitter.Status instances, one for each message ''' parameters = {} if since_id: parameters['since_id'] = since_id if include_rts: parameters['include_rts'] = 1 if include_entities: parameters['include_entities'] = 1 url = '%s/statuses/public_timeline.json' % self.base_url json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def FilterPublicTimeline(self, term, since_id=None): '''Filter the public twitter timeline by a given search term on the local machine. Args: term: term to search by. since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] Returns: A sequence of twitter.Status instances, one for each message containing the term ''' statuses = self.GetPublicTimeline(since_id) results = [] for s in statuses: if s.text.lower().find(term.lower()) != -1: results.append(s) return results def GetSearch(self, term=None, geocode=None, since_id=None, per_page=15, page=1, lang="en", show_user="true", query_users=False): '''Return twitter search results for a given term. Args: term: term to search by. Optional if you include geocode. since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] geocode: geolocation information in the form (latitude, longitude, radius) [Optional] per_page: number of results to return. Default is 15 [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] lang: language for results. Default is English [Optional] show_user: prefixes screen name in status query_users: If set to False, then all users only have screen_name and profile_image_url available. If set to True, all information of users are available, but it uses lots of request quota, one per status. Returns: A sequence of twitter.Status instances, one for each message containing the term ''' # Build request parameters parameters = {} if since_id: parameters['since_id'] = since_id if term is None and geocode is None: return [] if term is not None: parameters['q'] = term if geocode is not None: parameters['geocode'] = ','.join(map(str, geocode)) parameters['show_user'] = show_user parameters['lang'] = lang parameters['rpp'] = per_page parameters['page'] = page # Make and send requests url = 'http://search.twitter.com/search.json' json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) results = [] for x in data['results']: temp = Status.NewFromJsonDict(x) if query_users: # Build user object with new request temp.user = self.GetUser(urllib.quote(x['from_user'])) else: temp.user = User(screen_name=x['from_user'], profile_image_url=x['profile_image_url']) results.append(temp) # Return built list of statuses return results # [Status.NewFromJsonDict(x) for x in data['results']] def GetTrendsCurrent(self, exclude=None): '''Get the current top trending topics Args: exclude: Appends the exclude parameter as a request parameter. Currently only exclude=hashtags is supported. [Optional] Returns: A list with 10 entries. Each entry contains the twitter. ''' parameters = {} if exclude: parameters['exclude'] = exclude url = '%s/trends/current.json' % self.base_url json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) trends = [] for t in data['trends']: for item in data['trends'][t]: trends.append(Trend.NewFromJsonDict(item, timestamp = t)) return trends def GetTrendsWoeid(self, woeid, exclude=None): '''Return the top 10 trending topics for a specific WOEID, if trending information is available for it. Args: woeid: the Yahoo! Where On Earth ID for a location. exclude: Appends the exclude parameter as a request parameter. Currently only exclude=hashtags is supported. [Optional] Returns: A list with 10 entries. Each entry contains a Trend. ''' parameters = {} if exclude: parameters['exclude'] = exclude url = '%s/trends/%s.json' % (self.base_url, woeid) json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) trends = [] timestamp = data[0]['as_of'] for trend in data[0]['trends']: trends.append(Trend.NewFromJsonDict(trend, timestamp = timestamp)) return trends def GetTrendsDaily(self, exclude=None, startdate=None): '''Get the current top trending topics for each hour in a given day Args: startdate: The start date for the report. Should be in the format YYYY-MM-DD. [Optional] exclude: Appends the exclude parameter as a request parameter. Currently only exclude=hashtags is supported. [Optional] Returns: A list with 24 entries. Each entry contains the twitter. Trend elements that were trending at the corresponding hour of the day. ''' parameters = {} if exclude: parameters['exclude'] = exclude if not startdate: startdate = time.strftime('%Y-%m-%d', time.gmtime()) parameters['date'] = startdate url = '%s/trends/daily.json' % self.base_url json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) trends = [] for i in xrange(24): trends.append(None) for t in data['trends']: idx = int(time.strftime('%H', time.strptime(t, '%Y-%m-%d %H:%M'))) trends[idx] = [Trend.NewFromJsonDict(x, timestamp = t) for x in data['trends'][t]] return trends def GetTrendsWeekly(self, exclude=None, startdate=None): '''Get the top 30 trending topics for each day in a given week. Args: startdate: The start date for the report. Should be in the format YYYY-MM-DD. [Optional] exclude: Appends the exclude parameter as a request parameter. Currently only exclude=hashtags is supported. [Optional] Returns: A list with each entry contains the twitter. Trend elements of trending topics for the corrsponding day of the week ''' parameters = {} if exclude: parameters['exclude'] = exclude if not startdate: startdate = time.strftime('%Y-%m-%d', time.gmtime()) parameters['date'] = startdate url = '%s/trends/weekly.json' % self.base_url json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) trends = [] for i in xrange(7): trends.append(None) # use the epochs of the dates as keys for a dictionary times = dict([(calendar.timegm(time.strptime(t, '%Y-%m-%d')),t) for t in data['trends']]) cnt = 0 # create the resulting structure ordered by the epochs of the dates for e in sorted(times.keys()): trends[cnt] = [Trend.NewFromJsonDict(x, timestamp = times[e]) for x in data['trends'][times[e]]] cnt +=1 return trends def GetFriendsTimeline(self, user=None, count=None, page=None, since_id=None, retweets=None, include_entities=None): '''Fetch the sequence of twitter.Status messages for a user's friends The twitter.Api instance must be authenticated if the user is private. Args: user: Specifies the ID or screen name of the user for whom to return the friends_timeline. If not specified then the authenticated user set in the twitter.Api instance will be used. [Optional] count: Specifies the number of statuses to retrieve. May not be greater than 100. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] retweets: If True, the timeline will contain native retweets. [Optional] include_entities: If True, each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. [Optional] Returns: A sequence of twitter.Status instances, one for each message ''' if not user and not self._oauth_consumer: raise TwitterError("User must be specified if API is not authenticated.") url = '%s/statuses/friends_timeline' % self.base_url if user: url = '%s/%s.json' % (url, user) else: url = '%s.json' % url parameters = {} if count is not None: try: if int(count) > 100: raise TwitterError("'count' may not be greater than 100") except ValueError: raise TwitterError("'count' must be an integer") parameters['count'] = count if page is not None: try: parameters['page'] = int(page) except ValueError: raise TwitterError("'page' must be an integer") if since_id: parameters['since_id'] = since_id if retweets: parameters['include_rts'] = True if include_entities: parameters['include_entities'] = True json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def GetUserTimeline(self, id=None, user_id=None, screen_name=None, since_id=None, max_id=None, count=None, page=None, include_rts=None, include_entities=None): '''Fetch the sequence of public Status messages for a single user. The twitter.Api instance must be authenticated if the user is private. Args: id: Specifies the ID or screen name of the user for whom to return the user_timeline. [Optional] user_id: Specfies the ID of the user for whom to return the user_timeline. Helpful for disambiguating when a valid user ID is also a valid screen name. [Optional] screen_name: Specfies the screen name of the user for whom to return the user_timeline. Helpful for disambiguating when a valid screen name is also a user ID. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns only statuses with an ID less than (that is, older than) or equal to the specified ID. [Optional] count: Specifies the number of statuses to retrieve. May not be greater than 200. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] include_rts: If True, the timeline will contain native retweets (if they exist) in addition to the standard stream of tweets. [Optional] include_entities: If True, each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. [Optional] Returns: A sequence of Status instances, one for each message up to count ''' parameters = {} if id: url = '%s/statuses/user_timeline/%s.json' % (self.base_url, id) elif user_id: url = '%s/statuses/user_timeline.json?user_id=%d' % (self.base_url, user_id) elif screen_name: url = ('%s/statuses/user_timeline.json?screen_name=%s' % (self.base_url, screen_name)) elif not self._oauth_consumer: raise TwitterError("User must be specified if API is not authenticated.") else: url = '%s/statuses/user_timeline.json' % self.base_url if since_id: try: parameters['since_id'] = long(since_id) except: raise TwitterError("since_id must be an integer") if max_id: try: parameters['max_id'] = long(max_id) except: raise TwitterError("max_id must be an integer") if count: try: parameters['count'] = int(count) except: raise TwitterError("count must be an integer") if page: try: parameters['page'] = int(page) except: raise TwitterError("page must be an integer") if include_rts: parameters['include_rts'] = 1 if include_entities: parameters['include_entities'] = 1 json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def GetStatus(self, id, include_entities=None): '''Returns a single status message. The twitter.Api instance must be authenticated if the status message is private. Args: id: The numeric ID of the status you are trying to retrieve. include_entities: If True, each tweet will include a node called "entities". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. [Optional] Returns: A twitter.Status instance representing that status message ''' try: if id: long(id) except: raise TwitterError("id must be an long integer") parameters = {} if include_entities: parameters['include_entities'] = 1 url = '%s/statuses/show/%s.json' % (self.base_url, id) json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data) def DestroyStatus(self, id): '''Destroys the status specified by the required ID parameter. The twitter.Api instance must be authenticated and the authenticating user must be the author of the specified status. Args: id: The numerical ID of the status you're trying to destroy. Returns: A twitter.Status instance representing the destroyed status message ''' try: if id: long(id) except: raise TwitterError("id must be an integer") url = '%s/statuses/destroy/%s.json' % (self.base_url, id) json = self._FetchUrl(url, post_data={'id': id}) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data) @classmethod def _calculate_status_length(cls, status, linksize=19): dummy_link_replacement = 'https://-%d-chars%s/' % (linksize, '-'*(linksize - 18)) shortened = ' '.join([x if not (x.startswith('http://') or x.startswith('https://')) else dummy_link_replacement for x in status.split(' ')]) return len(shortened) def PostUpdate(self, status, in_reply_to_status_id=None): '''Post a twitter status message from the authenticated user. The twitter.Api instance must be authenticated. Args: status: The message text to be posted. Must be less than or equal to 140 characters. in_reply_to_status_id: The ID of an existing status that the status to be posted is in reply to. This implicitly sets the in_reply_to_user_id attribute of the resulting status to the user ID of the message being replied to. Invalid/missing status IDs will be ignored. [Optional] Returns: A twitter.Status instance representing the message posted. ''' if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") url = '%s/statuses/update.json' % self.base_url if isinstance(status, unicode) or self._input_encoding is None: u_status = status else: u_status = unicode(status, self._input_encoding) if self._calculate_status_length(u_status, self._shortlink_size) > CHARACTER_LIMIT: raise TwitterError("Text must be less than or equal to %d characters. " "Consider using PostUpdates." % CHARACTER_LIMIT) data = {'status': status} if in_reply_to_status_id: data['in_reply_to_status_id'] = in_reply_to_status_id json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data) def PostUpdates(self, status, continuation=None, **kwargs): '''Post one or more twitter status messages from the authenticated user. Unlike api.PostUpdate, this method will post multiple status updates if the message is longer than 140 characters. The twitter.Api instance must be authenticated. Args: status: The message text to be posted. May be longer than 140 characters. continuation: The character string, if any, to be appended to all but the last message. Note that Twitter strips trailing '...' strings from messages. Consider using the unicode \u2026 character (horizontal ellipsis) instead. [Defaults to None] **kwargs: See api.PostUpdate for a list of accepted parameters. Returns: A of list twitter.Status instance representing the messages posted. ''' results = list() if continuation is None: continuation = '' line_length = CHARACTER_LIMIT - len(continuation) lines = textwrap.wrap(status, line_length) for line in lines[0:-1]: results.append(self.PostUpdate(line + continuation, **kwargs)) results.append(self.PostUpdate(lines[-1], **kwargs)) return results def GetUserRetweets(self, count=None, since_id=None, max_id=None, include_entities=False): '''Fetch the sequence of retweets made by a single user. The twitter.Api instance must be authenticated. Args: count: The number of status messages to retrieve. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns results with an ID less than (that is, older than) or equal to the specified ID. [Optional] include_entities: If True, each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. [Optional] Returns: A sequence of twitter.Status instances, one for each message up to count ''' url = '%s/statuses/retweeted_by_me.json' % self.base_url if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") parameters = {} if count is not None: try: if int(count) > 100: raise TwitterError("'count' may not be greater than 100") except ValueError: raise TwitterError("'count' must be an integer") if count: parameters['count'] = count if since_id: parameters['since_id'] = since_id if include_entities: parameters['include_entities'] = True if max_id: try: parameters['max_id'] = long(max_id) except: raise TwitterError("max_id must be an integer") json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def GetReplies(self, since=None, since_id=None, page=None): '''Get a sequence of status messages representing the 20 most recent replies (status updates prefixed with @twitterID) to the authenticating user. Args: since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] since: Returns: A sequence of twitter.Status instances, one for each reply to the user. ''' url = '%s/statuses/replies.json' % self.base_url if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") parameters = {} if since: parameters['since'] = since if since_id: parameters['since_id'] = since_id if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def GetRetweets(self, statusid): '''Returns up to 100 of the first retweets of the tweet identified by statusid Args: statusid: The ID of the tweet for which retweets should be searched for Returns: A list of twitter.Status instances, which are retweets of statusid ''' if not self._oauth_consumer: raise TwitterError("The twitter.Api instsance must be authenticated.") url = '%s/statuses/retweets/%s.json?include_entities=true&include_rts=true' % (self.base_url, statusid) parameters = {} json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(s) for s in data] def GetFriends(self, user=None, cursor=-1): '''Fetch the sequence of twitter.User instances, one for each friend. The twitter.Api instance must be authenticated. Args: user: The twitter name or id of the user whose friends you are fetching. If not specified, defaults to the authenticated user. [Optional] Returns: A sequence of twitter.User instances, one for each friend ''' if not user and not self._oauth_consumer: raise TwitterError("twitter.Api instance must be authenticated") if user: url = '%s/statuses/friends/%s.json' % (self.base_url, user) else: url = '%s/statuses/friends.json' % self.base_url parameters = {} parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [User.NewFromJsonDict(x) for x in data['users']] def GetFriendIDs(self, user=None, cursor=-1): '''Returns a list of twitter user id's for every person the specified user is following. Args: user: The id or screen_name of the user to retrieve the id list for [Optional] Returns: A list of integers, one for each user id. ''' if not user and not self._oauth_consumer: raise TwitterError("twitter.Api instance must be authenticated") if user: url = '%s/friends/ids/%s.json' % (self.base_url, user) else: url = '%s/friends/ids.json' % self.base_url parameters = {} parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return data def GetFollowerIDs(self, userid=None, cursor=-1): '''Fetch the sequence of twitter.User instances, one for each follower The twitter.Api instance must be authenticated. Returns: A sequence of twitter.User instances, one for each follower ''' url = '%s/followers/ids.json' % self.base_url parameters = {} parameters['cursor'] = cursor if userid: parameters['user_id'] = userid json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return data def GetFollowers(self, cursor=-1): '''Fetch the sequence of twitter.User instances, one for each follower The twitter.Api instance must be authenticated. Args: cursor: Specifies the Twitter API Cursor location to start at. [Optional] Note: there are pagination limits. Returns: A sequence of twitter.User instances, one for each follower ''' if not self._oauth_consumer: raise TwitterError("twitter.Api instance must be authenticated") url = '%s/statuses/followers.json' % self.base_url result = [] while True: parameters = { 'cursor': cursor } json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) result += [User.NewFromJsonDict(x) for x in data['users']] if 'next_cursor' in data: if data['next_cursor'] == 0 or data['next_cursor'] == data['previous_cursor']: break else: break return result def GetFeatured(self): '''Fetch the sequence of twitter.User instances featured on twitter.com The twitter.Api instance must be authenticated. Returns: A sequence of twitter.User instances ''' url = '%s/statuses/featured.json' % self.base_url json = self._FetchUrl(url) data = self._ParseAndCheckTwitter(json) return [User.NewFromJsonDict(x) for x in data] def UsersLookup(self, user_id=None, screen_name=None, users=None): '''Fetch extended information for the specified users. Users may be specified either as lists of either user_ids, screen_names, or twitter.User objects. The list of users that are queried is the union of all specified parameters. The twitter.Api instance must be authenticated. Args: user_id: A list of user_ids to retrieve extended information. [Optional] screen_name: A list of screen_names to retrieve extended information. [Optional] users: A list of twitter.User objects to retrieve extended information. [Optional] Returns: A list of twitter.User objects for the requested users ''' if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") if not user_id and not screen_name and not users: raise TwitterError("Specify at least on of user_id, screen_name, or users.") url = '%s/users/lookup.json' % self.base_url parameters = {} uids = list() if user_id: uids.extend(user_id) if users: uids.extend([u.id for u in users]) if len(uids): parameters['user_id'] = ','.join(["%s" % u for u in uids]) if screen_name: parameters['screen_name'] = ','.join(screen_name) json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [User.NewFromJsonDict(u) for u in data] def GetUser(self, user): '''Returns a single user. The twitter.Api instance must be authenticated. Args: user: The twitter name or id of the user to retrieve. Returns: A twitter.User instance representing that user ''' url = '%s/users/show/%s.json' % (self.base_url, user) json = self._FetchUrl(url) data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data) def GetDirectMessages(self, since=None, since_id=None, page=None): '''Returns a list of the direct messages sent to the authenticating user. The twitter.Api instance must be authenticated. Args: since: Narrows the returned results to just those statuses created after the specified HTTP-formatted date. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] Returns: A sequence of twitter.DirectMessage instances ''' url = '%s/direct_messages.json' % self.base_url if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") parameters = {} if since: parameters['since'] = since if since_id: parameters['since_id'] = since_id if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [DirectMessage.NewFromJsonDict(x) for x in data] def PostDirectMessage(self, user, text): '''Post a twitter direct message from the authenticated user The twitter.Api instance must be authenticated. Args: user: The ID or screen name of the recipient user. text: The message text to be posted. Must be less than 140 characters. Returns: A twitter.DirectMessage instance representing the message posted ''' if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") url = '%s/direct_messages/new.json' % self.base_url data = {'text': text, 'user': user} json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return DirectMessage.NewFromJsonDict(data) def DestroyDirectMessage(self, id): '''Destroys the direct message specified in the required ID parameter. The twitter.Api instance must be authenticated, and the authenticating user must be the recipient of the specified direct message. Args: id: The id of the direct message to be destroyed Returns: A twitter.DirectMessage instance representing the message destroyed ''' url = '%s/direct_messages/destroy/%s.json' % (self.base_url, id) json = self._FetchUrl(url, post_data={'id': id}) data = self._ParseAndCheckTwitter(json) return DirectMessage.NewFromJsonDict(data) def CreateFriendship(self, user): '''Befriends the user specified in the user parameter as the authenticating user. The twitter.Api instance must be authenticated. Args: The ID or screen name of the user to befriend. Returns: A twitter.User instance representing the befriended user. ''' url = '%s/friendships/create/%s.json' % (self.base_url, user) json = self._FetchUrl(url, post_data={'user': user}) data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data) def DestroyFriendship(self, user): '''Discontinues friendship with the user specified in the user parameter. The twitter.Api instance must be authenticated. Args: The ID or screen name of the user with whom to discontinue friendship. Returns: A twitter.User instance representing the discontinued friend. ''' url = '%s/friendships/destroy/%s.json' % (self.base_url, user) json = self._FetchUrl(url, post_data={'user': user}) data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data) def CreateFavorite(self, status): '''Favorites the status specified in the status parameter as the authenticating user. Returns the favorite status when successful. The twitter.Api instance must be authenticated. Args: The twitter.Status instance to mark as a favorite. Returns: A twitter.Status instance representing the newly-marked favorite. ''' url = '%s/favorites/create/%s.json' % (self.base_url, status.id) json = self._FetchUrl(url, post_data={'id': status.id}) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data) def DestroyFavorite(self, status): '''Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful. The twitter.Api instance must be authenticated. Args: The twitter.Status to unmark as a favorite. Returns: A twitter.Status instance representing the newly-unmarked favorite. ''' url = '%s/favorites/destroy/%s.json' % (self.base_url, status.id) json = self._FetchUrl(url, post_data={'id': status.id}) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data) def GetFavorites(self, user=None, page=None): '''Return a list of Status objects representing favorited tweets. By default, returns the (up to) 20 most recent tweets for the authenticated user. Args: user: The twitter name or id of the user whose favorites you are fetching. If not specified, defaults to the authenticated user. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] ''' parameters = {} if page: parameters['page'] = page if user: url = '%s/favorites/%s.json' % (self.base_url, user) elif not user and not self._oauth_consumer: raise TwitterError("User must be specified if API is not authenticated.") else: url = '%s/favorites.json' % self.base_url json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def GetMentions(self, since_id=None, max_id=None, page=None): '''Returns the 20 most recent mentions (status containing @twitterID) for the authenticating user. Args: since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns only statuses with an ID less than (that is, older than) the specified ID. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] Returns: A sequence of twitter.Status instances, one for each mention of the user. ''' url = '%s/statuses/mentions.json' % self.base_url if not self._oauth_consumer: raise TwitterError("The twitter.Api instance must be authenticated.") parameters = {} if since_id: parameters['since_id'] = since_id if max_id: try: parameters['max_id'] = long(max_id) except: raise TwitterError("max_id must be an integer") if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data] def CreateList(self, user, name, mode=None, description=None): '''Creates a new list with the give name The twitter.Api instance must be authenticated. Args: user: Twitter name to create the list for name: New name for the list mode: 'public' or 'private'. Defaults to 'public'. [Optional] description: Description of the list. [Optional] Returns: A twitter.List instance representing the new list ''' url = '%s/%s/lists.json' % (self.base_url, user) parameters = {'name': name} if mode is not None: parameters['mode'] = mode if description is not None: parameters['description'] = description json = self._FetchUrl(url, post_data=parameters) data = self._ParseAndCheckTwitter(json) return List.NewFromJsonDict(data) def DestroyList(self, user, id): '''Destroys the list from the given user The twitter.Api instance must be authenticated. Args: user: The user to remove the list from. id: The slug or id of the list to remove. Returns: A twitter.List instance representing the removed list. ''' url = '%s/%s/lists/%s.json' % (self.base_url, user, id) json = self._FetchUrl(url, post_data={'_method': 'DELETE'}) data = self._ParseAndCheckTwitter(json) return List.NewFromJsonDict(data) def CreateSubscription(self, owner, list): '''Creates a subscription to a list by the authenticated user The twitter.Api instance must be authenticated. Args: owner: User name or id of the owner of the list being subscribed to. list: The slug or list id to subscribe the user to Returns: A twitter.List instance representing the list subscribed to ''' url = '%s/%s/%s/subscribers.json' % (self.base_url, owner, list) json = self._FetchUrl(url, post_data={'list_id': list}) data = self._ParseAndCheckTwitter(json) return List.NewFromJsonDict(data) def DestroySubscription(self, owner, list): '''Destroys the subscription to a list for the authenticated user The twitter.Api instance must be authenticated. Args: owner: The user id or screen name of the user that owns the list that is to be unsubscribed from list: The slug or list id of the list to unsubscribe from Returns: A twitter.List instance representing the removed list. ''' url = '%s/%s/%s/subscribers.json' % (self.base_url, owner, list) json = self._FetchUrl(url, post_data={'_method': 'DELETE', 'list_id': list}) data = self._ParseAndCheckTwitter(json) return List.NewFromJsonDict(data) def GetSubscriptions(self, user, cursor=-1): '''Fetch the sequence of Lists that the given user is subscribed to The twitter.Api instance must be authenticated. Args: user: The twitter name or id of the user cursor: "page" value that Twitter will use to start building the list sequence from. -1 to start at the beginning. Twitter will return in the result the values for next_cursor and previous_cursor. [Optional] Returns: A sequence of twitter.List instances, one for each list ''' if not self._oauth_consumer: raise TwitterError("twitter.Api instance must be authenticated") url = '%s/%s/lists/subscriptions.json' % (self.base_url, user) parameters = {} parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [List.NewFromJsonDict(x) for x in data['lists']] def GetLists(self, user, cursor=-1): '''Fetch the sequence of lists for a user. The twitter.Api instance must be authenticated. Args: user: The twitter name or id of the user whose friends you are fetching. If the passed in user is the same as the authenticated user then you will also receive private list data. cursor: "page" value that Twitter will use to start building the list sequence from. -1 to start at the beginning. Twitter will return in the result the values for next_cursor and previous_cursor. [Optional] Returns: A sequence of twitter.List instances, one for each list ''' if not self._oauth_consumer: raise TwitterError("twitter.Api instance must be authenticated") url = '%s/%s/lists.json' % (self.base_url, user) parameters = {} parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [List.NewFromJsonDict(x) for x in data['lists']] def GetUserByEmail(self, email): '''Returns a single user by email address. Args: email: The email of the user to retrieve. Returns: A twitter.User instance representing that user ''' url = '%s/users/show.json?email=%s' % (self.base_url, email) json = self._FetchUrl(url) data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data) def VerifyCredentials(self): '''Returns a twitter.User instance if the authenticating user is valid. Returns: A twitter.User instance representing that user if the credentials are valid, None otherwise. ''' if not self._oauth_consumer: raise TwitterError("Api instance must first be given user credentials.") url = '%s/account/verify_credentials.json' % self.base_url try: json = self._FetchUrl(url, no_cache=True) except urllib2.HTTPError, http_error: if http_error.code == httplib.UNAUTHORIZED: return None else: raise http_error data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data) def SetCache(self, cache): '''Override the default cache. Set to None to prevent caching. Args: cache: An instance that supports the same API as the twitter._FileCache ''' if cache == DEFAULT_CACHE: self._cache = _FileCache() else: self._cache = cache def SetUrllib(self, urllib): '''Override the default urllib implementation. Args: urllib: An instance that supports the same API as the urllib2 module ''' self._urllib = urllib def SetCacheTimeout(self, cache_timeout): '''Override the default cache timeout. Args: cache_timeout: Time, in seconds, that responses should be reused. ''' self._cache_timeout = cache_timeout def SetUserAgent(self, user_agent): '''Override the default user agent Args: user_agent: A string that should be send to the server as the User-agent ''' self._request_headers['User-Agent'] = user_agent def SetXTwitterHeaders(self, client, url, version): '''Set the X-Twitter HTTP headers that will be sent to the server. Args: client: The client name as a string. Will be sent to the server as the 'X-Twitter-Client' header. url: The URL of the meta.xml as a string. Will be sent to the server as the 'X-Twitter-Client-URL' header. version: The client version as a string. Will be sent to the server as the 'X-Twitter-Client-Version' header. ''' self._request_headers['X-Twitter-Client'] = client self._request_headers['X-Twitter-Client-URL'] = url self._request_headers['X-Twitter-Client-Version'] = version def SetSource(self, source): '''Suggest the "from source" value to be displayed on the Twitter web site. The value of the 'source' parameter must be first recognized by the Twitter server. New source values are authorized on a case by case basis by the Twitter development team. Args: source: The source name as a string. Will be sent to the server as the 'source' parameter. ''' self._default_params['source'] = source def GetRateLimitStatus(self): '''Fetch the rate limit status for the currently authorized user. Returns: A dictionary containing the time the limit will reset (reset_time), the number of remaining hits allowed before the reset (remaining_hits), the number of hits allowed in a 60-minute period (hourly_limit), and the time of the reset in seconds since The Epoch (reset_time_in_seconds). ''' url = '%s/account/rate_limit_status.json' % self.base_url json = self._FetchUrl(url, no_cache=True) data = self._ParseAndCheckTwitter(json) return data def MaximumHitFrequency(self): '''Determines the minimum number of seconds that a program must wait before hitting the server again without exceeding the rate_limit imposed for the currently authenticated user. Returns: The minimum second interval that a program must use so as to not exceed the rate_limit imposed for the user. ''' rate_status = self.GetRateLimitStatus() reset_time = rate_status.get('reset_time', None) limit = rate_status.get('remaining_hits', None) if reset_time: # put the reset time into a datetime object reset = datetime.datetime(*rfc822.parsedate(reset_time)[:7]) # find the difference in time between now and the reset time + 1 hour delta = reset + datetime.timedelta(hours=1) - datetime.datetime.utcnow() if not limit: return int(delta.seconds) # determine the minimum number of seconds allowed as a regular interval max_frequency = int(delta.seconds / limit) + 1 # return the number of seconds return max_frequency return 60 def _BuildUrl(self, url, path_elements=None, extra_params=None): # Break url into consituent parts (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url) # Add any additional path elements to the path if path_elements: # Filter out the path elements that have a value of None p = [i for i in path_elements if i] if not path.endswith('/'): path += '/' path += '/'.join(p) # Add any additional query parameters to the query string if extra_params and len(extra_params) > 0: extra_query = self._EncodeParameters(extra_params) # Add it to the existing query if query: query += '&' + extra_query else: query = extra_query # Return the rebuilt URL return urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) def _InitializeRequestHeaders(self, request_headers): if request_headers: self._request_headers = request_headers else: self._request_headers = {} def _InitializeUserAgent(self): user_agent = 'Python-urllib/%s (python-twitter/%s)' % \ (self._urllib.__version__, __version__) self.SetUserAgent(user_agent) def _InitializeDefaultParameters(self): self._default_params = {} def _DecompressGzippedResponse(self, response): raw_data = response.read() if response.headers.get('content-encoding', None) == 'gzip': url_data = gzip.GzipFile(fileobj=StringIO.StringIO(raw_data)).read() else: url_data = raw_data return url_data def _Encode(self, s): if self._input_encoding: return unicode(s, self._input_encoding).encode('utf-8') else: return unicode(s).encode('utf-8') def _EncodeParameters(self, parameters): '''Return a string in key=value&key=value form Values of None are not included in the output string. Args: parameters: A dict of (key, value) tuples, where value is encoded as specified by self._encoding Returns: A URL-encoded string in "key=value&key=value" form ''' if parameters is None: return None else: return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in parameters.items() if v is not None])) def _EncodePostData(self, post_data): '''Return a string in key=value&key=value form Values are assumed to be encoded in the format specified by self._encoding, and are subsequently URL encoded. Args: post_data: A dict of (key, value) tuples, where value is encoded as specified by self._encoding Returns: A URL-encoded string in "key=value&key=value" form ''' if post_data is None: return None else: return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in post_data.items()])) def _ParseAndCheckTwitter(self, json): """Try and parse the JSON returned from Twitter and return an empty dictionary if there is any error. This is a purely defensive check because during some Twitter network outages it will return an HTML failwhale page.""" try: data = simplejson.loads(json) self._CheckForTwitterError(data) except ValueError: if "<title>Twitter / Over capacity</title>" in json: raise TwitterError("Capacity Error") if "<title>Twitter / Error</title>" in json: raise TwitterError("Technical Error") raise TwitterError("json decoding") return data def _CheckForTwitterError(self, data): """Raises a TwitterError if twitter returns an error message. Args: data: A python dict created from the Twitter json response Raises: TwitterError wrapping the twitter error message if one exists. """ # Twitter errors are relatively unlikely, so it is faster # to check first, rather than try and catch the exception if 'error' in data: raise TwitterError(data['error']) if 'errors' in data: raise TwitterError(data['errors']) def _FetchUrl(self, url, post_data=None, parameters=None, no_cache=None, use_gzip_compression=None): '''Fetch a URL, optionally caching for a specified time. Args: url: The URL to retrieve post_data: A dict of (str, unicode) key/value pairs. If set, POST will be used. parameters: A dict whose key/value pairs should encoded and added to the query string. [Optional] no_cache: If true, overrides the cache on the current request use_gzip_compression: If True, tells the server to gzip-compress the response. It does not apply to POST requests. Defaults to None, which will get the value to use from the instance variable self._use_gzip [Optional] Returns: A string containing the body of the response. ''' # Build the extra parameters dict extra_params = {} if self._default_params: extra_params.update(self._default_params) if parameters: extra_params.update(parameters) if post_data: http_method = "POST" else: http_method = "GET" if self._debugHTTP: _debug = 1 else: _debug = 0 http_handler = self._urllib.HTTPHandler(debuglevel=_debug) https_handler = self._urllib.HTTPSHandler(debuglevel=_debug) opener = self._urllib.OpenerDirector() opener.add_handler(http_handler) opener.add_handler(https_handler) if use_gzip_compression is None: use_gzip = self._use_gzip else: use_gzip = use_gzip_compression # Set up compression if use_gzip and not post_data: opener.addheaders.append(('Accept-Encoding', 'gzip')) if self._oauth_consumer is not None: if post_data and http_method == "POST": parameters = post_data.copy() req = oauth.Request.from_consumer_and_token(self._oauth_consumer, token=self._oauth_token, http_method=http_method, http_url=url, parameters=parameters) req.sign_request(self._signature_method_hmac_sha1, self._oauth_consumer, self._oauth_token) headers = req.to_header() if http_method == "POST": encoded_post_data = req.to_postdata() else: encoded_post_data = None url = req.to_url() else: url = self._BuildUrl(url, extra_params=extra_params) encoded_post_data = self._EncodePostData(post_data) # Open and return the URL immediately if we're not going to cache if encoded_post_data or no_cache or not self._cache or not self._cache_timeout: response = opener.open(url, encoded_post_data) url_data = self._DecompressGzippedResponse(response) opener.close() else: # Unique keys are a combination of the url and the oAuth Consumer Key if self._consumer_key: key = self._consumer_key + ':' + url else: key = url # See if it has been cached before last_cached = self._cache.GetCachedTime(key) # If the cached version is outdated then fetch another and store it if not last_cached or time.time() >= last_cached + self._cache_timeout: try: response = opener.open(url, encoded_post_data) url_data = self._DecompressGzippedResponse(response) self._cache.Set(key, url_data) except urllib2.HTTPError, e: print e opener.close() else: url_data = self._cache.Get(key) # Always return the latest version return url_data class _FileCacheError(Exception): '''Base exception class for FileCache related errors''' class _FileCache(object): DEPTH = 3 def __init__(self,root_directory=None): self._InitializeRootDirectory(root_directory) def Get(self,key): path = self._GetPath(key) if os.path.exists(path): return open(path).read() else: return None def Set(self,key,data): path = self._GetPath(key) directory = os.path.dirname(path) if not os.path.exists(directory): os.makedirs(directory) if not os.path.isdir(directory): raise _FileCacheError('%s exists but is not a directory' % directory) temp_fd, temp_path = tempfile.mkstemp() temp_fp = os.fdopen(temp_fd, 'w') temp_fp.write(data) temp_fp.close() if not path.startswith(self._root_directory): raise _FileCacheError('%s does not appear to live under %s' % (path, self._root_directory)) if os.path.exists(path): os.remove(path) os.rename(temp_path, path) def Remove(self,key): path = self._GetPath(key) if not path.startswith(self._root_directory): raise _FileCacheError('%s does not appear to live under %s' % (path, self._root_directory )) if os.path.exists(path): os.remove(path) def GetCachedTime(self,key): path = self._GetPath(key) if os.path.exists(path): return os.path.getmtime(path) else: return None def _GetUsername(self): '''Attempt to find the username in a cross-platform fashion.''' try: return os.getenv('USER') or \ os.getenv('LOGNAME') or \ os.getenv('USERNAME') or \ os.getlogin() or \ 'nobody' except (AttributeError, IOError, OSError), e: return 'nobody' def _GetTmpCachePath(self): username = self._GetUsername() cache_directory = 'python.cache_' + username return os.path.join(tempfile.gettempdir(), cache_directory) def _InitializeRootDirectory(self, root_directory): if not root_directory: root_directory = self._GetTmpCachePath() root_directory = os.path.abspath(root_directory) if not os.path.exists(root_directory): os.mkdir(root_directory) if not os.path.isdir(root_directory): raise _FileCacheError('%s exists but is not a directory' % root_directory) self._root_directory = root_directory def _GetPath(self,key): try: hashed_key = md5(key).hexdigest() except TypeError: hashed_key = md5.new(key).hexdigest() return os.path.join(self._root_directory, self._GetPrefix(hashed_key), hashed_key) def _GetPrefix(self,hashed_key): return os.path.sep.join(hashed_key[0:_FileCache.DEPTH])
Python
# editcarddialog.py # this is a dialog to allow the user to edit a card. import sys from PyQt4 import QtGui, QtCore from flashcard import * class EditCardDialog(QtGui.QDialog): def __init__(self, card, parent = None): QtGui.QDialog.__init__(self, parent) self.card = card #print self.card.values['english'] self.setWindowTitle('Edit Card') self.layout = QtGui.QHBoxLayout(self) self.columns = [QtGui.QVBoxLayout(), QtGui.QVBoxLayout()] self.handles = {} # handles into the contents of the widgets on this dialog self.typeSelect = QtGui.QComboBox(self) self.typeSelect.addItems(self.card.vocab.wordtypes.keys()) self.previousType = None for i in range(0, self.typeSelect.count()): if self.card.wordType.name == self.typeSelect.itemText(i): self.typeSelect.setCurrentIndex(i) self.columns[0].addWidget(self.typeSelect) columnIndex = 1 for field in self.card.vocab.wordtypes[str(self.typeSelect.currentText())].fields: (editWidget, self.handles[field.name]) = field.generateEditLayout(self.card.values[field.name]) self.columns[columnIndex].addLayout(editWidget) columnIndex += 1 if columnIndex >= len(self.columns): columnIndex = 0 self.okButton = QtGui.QPushButton('Save', self) self.cancelButton = QtGui.QPushButton('Cancel', self) self.columns[0].addWidget(self.okButton) self.columns[1].addWidget(self.cancelButton) for column in self.columns: self.layout.addLayout(column) self.connect(self.typeSelect, QtCore.SIGNAL('currentIndexChanged(int)'), self.changeWordType) self.connect(self.okButton, QtCore.SIGNAL('clicked()'), self.ok) self.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.cancel) def changeWordType(self, index): if self.previousType == None: self.previousType = self.card.wordType self.card.wordType = self.card.vocab.wordtypes[str(self.typeSelect.currentText())] for field in self.card.wordType.fields: if field.name not in self.card.values.keys(): self.card.values[field.name] = '' #if len(self.card.guiArea) > 0: # self.card.redoLayout() # now need to change the fields in this dialog to reflect new wordtype # easiest way to do this (but probably not the best) is close this dialog and open a new one. if self.__class__.__name__ == "EditCardDialog": self.card.vocab.dialog = EditCardDialog(self.card, self.card.vocab.mainGui) else: self.card.vocab.dialog = NewCardDialog(self.card.vocab, self.card, self.card.vocab.mainGui) self.card.vocab.dialog.show() self.close() def ok(self): values = {} for fieldName in self.handles: values[fieldName] = unicode(self.handles[fieldName].text()) self.card.values = values self.card.redoLayout() self.card.vocab.cardChanged(self.card) #newCard = FlashCard(self.card.vocab, self.card.vocab.mainGui, str(self.typeSelect.currentText()), values) #self.card = newCard #self.card.vocab.replaceCard(self.card, newCard) #if self.card.vocab.isActive(newCard): # self.card.vocab.activeCards.setCurrentWidget(newCard) # self.card.vocab.resetCurrentCard() self.card.vocab.changed = True self.close() def cancel(self): if not self.previousType == None: self.card.wordType = self.previousType # if len(self.card.guiArea) > 0: # self.card.redoLayout() self.close() class NewCardDialog(EditCardDialog): def __init__(self, vocab, card = None, parent = None): newCard = None if (card == None): newCard = FlashCard(vocab, vocab.mainGui, vocab.wordtypes.keys()[0], vocab.defaultCardValues) else: newCard = card.copy() EditCardDialog.__init__(self, newCard, parent) self.setWindowTitle('New Card') self.againButton = QtGui.QPushButton('Save and add another', self) self.columns[0].addWidget(self.againButton) self.connect(self.againButton, QtCore.SIGNAL('clicked()'), self.again) def ok(self): self.card.vocab.cards.append(self.card) if self.card.vocab.activeCards.count() > 0: self.card.vocab.activeCards.insertWidget(self.card.vocab.activeCards.currentIndex() + 1, self.card) self.card.vocab.progress.setRange(0, self.card.vocab.progress.maximum() + 1) EditCardDialog.ok(self) self.card.vocab.mainGui.setCardActionsEnabled(True) def again(self): self.ok() #QtGui.QMessageBox.information(self, 'Card saved', 'Card saved', QtGui.QMessageBox.Ok) self.card.vocab.newCard(self.card) def cancel(self): self.close()
Python
# activecarddialog.py # this is a dialog to allow the user to specify which cards from the vocab to be active import sys from PyQt4 import QtGui, QtCore class ActiveCardDialog(QtGui.QDialog): def __init__(self, vocab, parent=None): QtGui.QDialog.__init__(self, parent) self.vocab = vocab self.setWindowTitle('Select Active Cards') self.layout = QtGui.QGridLayout(self) chapterValidator = QtGui.QIntValidator(0, 300, self) difficultyValidator = QtGui.QDoubleValidator(-500, 500, 2, self) self.chLoEdit = QtGui.QLineEdit() self.chLoEdit.setValidator(chapterValidator) self.chLoEdit.setFixedWidth(40) self.chHiEdit = QtGui.QLineEdit() self.chHiEdit.setValidator(chapterValidator) self.chHiEdit.setFixedWidth(40) self.difLoEdit = QtGui.QLineEdit() self.difLoEdit.setValidator(difficultyValidator) self.difLoEdit.setFixedWidth(40) self.difHiEdit = QtGui.QLineEdit() self.difHiEdit.setValidator(difficultyValidator) self.difHiEdit.setFixedWidth(40) self.englishSearch = QtGui.QLineEdit() self.foreignSearch = QtGui.QLineEdit() self.layout.addWidget(QtGui.QLabel('Chapters:', self), 0, 0) self.layout.addWidget(QtGui.QLabel('from', self), 0, 1) self.layout.addWidget(self.chLoEdit, 0, 2) self.layout.addWidget(QtGui.QLabel('to', self), 0, 3) self.layout.addWidget(self.chHiEdit, 0, 4) self.layout.addWidget(QtGui.QLabel('Difficulty:', self), 1, 0) self.layout.addWidget(QtGui.QLabel('from', self), 1, 1) self.layout.addWidget(self.difLoEdit, 1, 2) self.layout.addWidget(QtGui.QLabel('to', self), 1, 3) self.layout.addWidget(self.difHiEdit, 1, 4) self.layout.addWidget(QtGui.QLabel('English:', self), 2, 0) self.layout.addWidget(QtGui.QLabel('contains', self), 2, 1) self.layout.addWidget(self.englishSearch, 2, 2, 1, 3) self.layout.addWidget(QtGui.QLabel('Foreign:', self), 3, 0) self.layout.addWidget(QtGui.QLabel('contains', self), 3, 1) self.layout.addWidget(self.foreignSearch, 3, 2, 1, 3) self.checkBoxes = {} columns = 2 column = 0 row = 4 width = 2 for wordtype in self.vocab.wordtypes: self.checkBoxes[wordtype] = QtGui.QCheckBox(wordtype, self) self.checkBoxes[wordtype].setChecked(True) self.layout.addWidget(self.checkBoxes[wordtype], row, column * width, 1, width + column) column += 1 if column >= columns: column = 0 row += 1 self.okButton = QtGui.QPushButton('OK', self) self.cancelButton = QtGui.QPushButton('Cancel', self) row = self.layout.rowCount() self.layout.addWidget(self.okButton, row, 1, 1, 2) self.layout.addWidget(self.cancelButton, row, 3, 1, 2) self.connect(self.okButton, QtCore.SIGNAL('clicked()'), self.ok) self.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.cancel) def ok(self): numbers = {} words = {} wordtypes = [] # if neither the hi nor lo entred we ignore that field, but if only one of the two entred we put something sensible in the other. if not (str(self.chLoEdit.text()) == '' and str(self.chHiEdit.text()) == ''): if str(self.chLoEdit.text()) == '': chLo = 0 else: chLo = int(self.chLoEdit.text()) if str(self.chHiEdit.text()) == '': chHi = 300 else: chHi = int(self.chHiEdit.text()) numbers['chapter'] = (chLo, chHi) if not (str(self.difLoEdit.text()) == '' and str(self.difHiEdit.text()) == ''): if str(self.difLoEdit.text()) == '': difLo = -500 else: difLo = float(self.difLoEdit.text()) if str(self.difHiEdit.text()) == '': difHi = 500 else: difHi = float(self.difHiEdit.text()) numbers['difficulty'] = (difLo, difHi) if not self.englishSearch.text() == '': words['english'] = unicode(self.englishSearch.text()) if not self.foreignSearch.text() == '': words['foreign'] = unicode(self.foreignSearch.text()) for wordtype in self.vocab.wordtypes: if self.checkBoxes[wordtype].isChecked(): wordtypes.append(wordtype) self.vocab.activeCardFilter = CardFilter(numbers, words, wordtypes) self.vocab.setActiveCards() self.hide() def cancel(self): self.hide() class CardFilter: def __init__(self, numbers, words, wordtypes, allCards = False): self.numbers = numbers self.words = words self.wordtypes = wordtypes self.allCards = allCards def filterCard(self, card): if self.allCards: print 'x' return True for fieldName in self.numbers: (min, max) = self.numbers[fieldName] if float(card.values[fieldName]) < min or float(card.values[fieldName]) > max: return False for fieldName in self.words: if not self.words[fieldName] in card.values[fieldName]: return False if card.wordType.name in self.wordtypes: return True else: return False
Python
# unicodecsv.py # the csv module doesn't handle unicode, so we need this stuff too. # I'm pretty sure there's overkill here for my purposes, but since I copied the code directly # from the docs and don't fully understand it, I can't edit it to my likings. import csv, codecs, cStringIO def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs): # csv.py doesn't do Unicode; encode temporarily as UTF-8: csv_reader = csv.reader(utf_8_encoder(unicode_csv_data), dialect=dialect, **kwargs) for row in csv_reader: # decode UTF-8 back to Unicode, cell by cell: yield [unicode(cell, 'utf-8') for cell in row] def utf_8_encoder(unicode_csv_data): for line in unicode_csv_data: yield line.encode('utf-8') class UnicodeWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = cStringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = codecs.getincrementalencoder(encoding)() def writerow(self, row): self.writer.writerow([s.encode("utf-8") for s in row]) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.decode("utf-8") # ... and reencode it into the target encoding data = self.encoder.encode(data) # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) def writerows(self, rows): for row in rows: self.writerow(row)
Python
# editcarddialog.py # this is a dialog to allow the user to edit the word types. from PyQt4 import QtGui, QtCore from wordtype import * class WordTypeDialog(QtGui.QDialog): def __init__(self, vocab, parent = None): QtGui.QDialog.__init__(self, parent) self.setWindowTitle('Edit Word Types') self.vocab = vocab self.tabPane = QtGui.QTabWidget(self) self.tabs = {} self.newWordTypeTabs = {} for wordtype in self.vocab.wordtypes: #page = QtGui.QScrollArea() self.tabs[wordtype] = WordTypeEditPane(self.vocab.wordtypes[wordtype]) #page.setWidget(self.tabs[wordtype]) #self.tabPane.addTab(page, self.vocab.wordtypes[wordtype].name) self.tabPane.addTab(self.tabs[wordtype], self.vocab.wordtypes[wordtype].name) self.mainLayout = QtGui.QVBoxLayout() self.mainLayout.addWidget(self.tabPane) self.newWordType = QtGui.QPushButton('New Word Type') self.newWordType.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) self.mainLayout.addWidget(self.newWordType) self.buttonPane = QtGui.QWidget() self.buttonPaneLayout = QtGui.QHBoxLayout() self.okButton = QtGui.QPushButton('OK') self.cancelButton = QtGui.QPushButton('Cancel') self.buttonPaneLayout.addWidget(self.okButton) self.buttonPaneLayout.addWidget(self.cancelButton) self.buttonPaneLayout.addStretch() self.buttonPane.setLayout(self.buttonPaneLayout) self.mainLayout.addWidget(self.buttonPane) self.setLayout(self.mainLayout) self.connect(self.okButton, QtCore.SIGNAL('clicked()'), self.ok) self.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.cancel) self.connect(self.newWordType, QtCore.SIGNAL('clicked()'), self.makeWordType) def ok(self): # first add the newly created wordtypes in for newWordTypeName in self.newWordTypeTabs: if not self.newWordTypeTabs[newWordTypeName].forDeletion: self.vocab.wordtypes[newWordTypeName] = self.newWordTypeTabs[newWordTypeName].wordtype self.tabs[newWordTypeName] = self.newWordTypeTabs[newWordTypeName] # next delete all the deleted word types for wordtype in self.tabs: if self.tabs[wordtype].forDeletion: del self.vocab.wordtypes[wordtype] for card in self.vocab.cards: if card.wordType.name == wordtype: card.wordType = self.vocab.wordtypes[self.tabs[wordtype].changeTo] else: # for all the wordtypes that aren't being deleted... # update the updated fields for i in range(0, len(self.tabs[wordtype].fields)): fieldME = self.tabs[wordtype].fields[i] if not fieldME.deleteMe: self.vocab.wordtypes[wordtype].fields[i].label = str(fieldME.labelEdit.text()) self.vocab.wordtypes[wordtype].fields[i].position = fieldPositionLabel[str(fieldME.selectPosition.currentText())] self.vocab.wordtypes[wordtype].fields[i].show = fieldShowLabel[str(fieldME.selectShow.currentText())] self.vocab.wordtypes[wordtype].fields[i].font = str(fieldME.selectFont.currentText()) # delete the deleted fields for i in range(0, len(self.tabs[wordtype].fields)): fieldME = self.tabs[wordtype].fields[i] if fieldME.deleteMe: self.vocab.wordtypes[wordtype].deleteField(fieldME.field.name) # add the new fields for i in range(0, len(self.tabs[wordtype].newFields)): fieldME = self.tabs[wordtype].newFields[i] if not fieldME.deleteMe: fieldME.field.label = str(fieldME.labelEdit.text()) fieldME.field.position = fieldPositionLabel[str(fieldME.selectPosition.currentText())] fieldME.field.show = fieldShowLabel[str(fieldME.selectShow.currentText())] fieldME.field.font = str(fieldME.selectFont.currentText()) self.vocab.wordtypes[wordtype].fields.append(fieldME.field) self.close() self.vocab.changed = True self.vocab.refreshAllCards() def cancel(self): self.close() def makeWordType(self): (wordTypeName, ok) = QtGui.QInputDialog.getText(self, 'New Word Type Name', 'Enter a name for the word type') if ok: if wordTypeName in self.vocab.wordtypes.keys(): QtGui.QMessageBox.information(self, 'Word type already exists', "%s already exists as a word type in this vocab" % (wordTypeName)) else: if len(self.vocab.wordtypes) < 2: self.tabs[self.tabs.keys()[0]].deleteWordtypeButton.setEnabled(True) fields = [] # there are 4 compulsory fields in a wordtype, should be found as the first four fields in the first wordtype if len(self.vocab.wordtypes): firstWordType = self.vocab.wordtypes.keys()[0] for i in range(0,4): fields.append(self.vocab.wordtypes[firstWordType].fields[i].copy()) else: compulsory = ['chapter', 'difficulty', 'english', 'foreign'] for fieldName in compulsory: fields.append(Field(self.wordtype.vocab, fieldName, fieldName, self.wordtype.vocab.fonts.keys()[0], FieldPosition.LEFT, FieldShow.ALWAYS)) page = QtGui.QScrollArea() self.newWordTypeTabs[wordTypeName] = WordTypeEditPane(WordType(self.vocab, wordTypeName, fields)) page.setWidget(self.newWordTypeTabs[wordTypeName]) self.tabPane.addTab(page, wordTypeName) self.tabPane.setCurrentIndex(self.tabPane.count() - 1) class WordTypeEditPane(QtGui.QWidget): def __init__(self, wordtype, parent = None): QtGui.QWidget.__init__(self, parent) self.wordtype = wordtype self.pageLayout = QtGui.QVBoxLayout() self.setLayout(self.pageLayout) self.deleteWordtypeLayout = QtGui.QHBoxLayout() self.deleteWordtypeButton = QtGui.QPushButton('Delete this wordtype') if len(self.wordtype.vocab.wordtypes) < 2: self.deleteWordtypeButton.setEnabled(False) self.deleteWordtypeLabel = QtGui.QLabel('and change any ' + self.wordtype.name + ' cards into:') self.changeWordsTo = QtGui.QComboBox() items = self.wordtype.vocab.wordtypes.keys() assert items.count(self.wordtype.name) <= 1 if items.count(self.wordtype.name) > 0: items.remove(self.wordtype.name) self.changeWordsTo.addItems(items) self.deleteWordtypeLayout.addWidget(self.deleteWordtypeButton) self.deleteWordtypeLayout.addWidget(self.deleteWordtypeLabel) self.deleteWordtypeLayout.addWidget(self.changeWordsTo) self.pageLayout.addLayout(self.deleteWordtypeLayout) self.forDeletion = False self.changeTo = None self.fields = [] self.newFields = [] self.fieldEditGrid = QtGui.QGridLayout() self.fieldEditGrid.addWidget(QtGui.QLabel('Field Name'), 0, 1) self.fieldEditGrid.addWidget(QtGui.QLabel('Label'), 0, 2) self.fieldEditGrid.addWidget(QtGui.QLabel('Position'), 0, 3) self.fieldEditGrid.addWidget(QtGui.QLabel('Show'), 0, 4) self.fieldEditGrid.addWidget(QtGui.QLabel('Font'), 0, 5) for i in range(0, len(self.wordtype.fields)): self.fields.append(FieldMetaEdit(self.wordtype.fields[i], self.fieldEditGrid, self)) self.pageLayout.addLayout(self.fieldEditGrid) self.pageLayout.addStretch() self.newField = QtGui.QPushButton('New Field') self.newField.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) self.pageLayout.addWidget(self.newField) #self.setSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum) self.connect(self.newField, QtCore.SIGNAL('clicked()'), self.makeNewField) self.connect(self.deleteWordtypeButton, QtCore.SIGNAL('clicked()'), self.deleteWordtype) def deleteWordtype(self): reply = QtGui.QMessageBox.question( self, "Delete %s?" % (self.wordtype.name), "Are you sure you want to delete the %s word type and change all %s cards into %s cards?" % (self.wordtype.name, self.wordtype.name, self.changeWordsTo.currentText()), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: self.forDeletion = True self.changeTo = str(self.changeWordsTo.currentText()) # tabPane.removeTab(tabPane.indexOf(page)) self.parent().parent().parent().parent().removeTab(self.parent().parent().parent().parent().indexOf(self.parent().parent())) def makeNewField(self): (fieldName, ok) = QtGui.QInputDialog.getText(self, 'New Field Name', 'Enter a name for the field') if ok: newFieldME = FieldMetaEdit( Field( self.wordtype.vocab,fieldName,fieldName, self.wordtype.vocab.fonts.keys()[0], FieldPosition.LEFT, FieldShow.ALWAYS), self.fieldEditGrid, self) self.newFields.append(newFieldME)
Python
# wordtype.py # each word has its own configuarble fields from PyQt4 import QtGui, QtCore class WordType: def __init__(self, parent, name, fields): self.vocab = parent self.name = name self.fields = fields # this should be an array def deleteField(self, fieldName): for field in self.fields: if field.name == fieldName: self.fields.remove(field) break def toCSV(self, csvWriter): csvWriter.writerow([self.name]) for field in self.fields: field.toCSV(csvWriter) csvWriter.writerow(['/' + self.name]) def writeXML(self, xmlWriter): xmlWriter.writeStartElement('wordType') xmlWriter.writeAttribute('name', self.name) for field in self.fields: field.writeXML(xmlWriter) xmlWriter.writeEndElement() class Field: def __init__(self, vocab, name, label, font, position, show): self.vocab = vocab self.name = str(name) self.label = str(label) # for the UI #self.font = QtGui.QFont() # the font to use for the value string #self.font.fromString(font) self.font = str(font) # refers to a particular font in vocab.fonts self.position = int(position) # where we put it on the flashcard self.show = int(show) # when we reveal this field def instantiate(self, value, parent): assert(self.position != FieldPosition.PREFIX) assert(self.position != FieldPosition.POSTFIX) return FieldInstance(self, value, parent) def generateEditLayout(self, value): editLayout = QtGui.QHBoxLayout() editLabel = QtGui.QLabel(self.label) editLabel.setAlignment(QtCore.Qt.AlignRight) editLayout.addWidget(editLabel) editValue = QtGui.QLineEdit(unicode(value)) # some special cases where we need to make sure a reasonable int is entered if self.name == 'chapter': validator = QtGui.QIntValidator(None) validator.setBottom(0) editValue.setValidator(validator) elif self.name == 'difficulty': validator = QtGui.QDoubleValidator(None) editValue.setValidator(validator) editFont = QtGui.QFont(self.vocab.fonts[self.font]) editFont.setPointSize(12) editValue.setFont(editFont) editValue.setAlignment(QtCore.Qt.AlignLeft) editLayout.addWidget(editValue) return (editLayout, editValue) def toCSV(self, csvWriter): csvWriter.writerow([self.name, self.label, self.font, str(self.position), str(self.show)]) def writeXML(self, xmlWriter): xmlWriter.writeStartElement('field') xmlWriter.writeAttribute('name', self.name) xmlWriter.writeTextElement('label', self.label) xmlWriter.writeTextElement('font', self.font) xmlWriter.writeTextElement('position', str(self.position)) xmlWriter.writeTextElement('show', str(self.show)) xmlWriter.writeEndElement() def copy(self): return Field(self.vocab, self.name, self.label, self.font, self.position, self.show) class FieldInstance: def __init__(self, field, value, parent = None): self.field = field self.value = value self.layout = QtGui.QHBoxLayout() if self.field.name != 'english' and self.field.name != 'foreign': self.labelLabel = QtGui.QLabel(field.label + ':') self.labelLabel.setAlignment(QtCore.Qt.AlignRight) self.layout.addWidget(self.labelLabel) self.valueLabel = QtGui.QLabel(self.value) self.valueLabel.setFont(field.vocab.fonts[field.font]) if self.field.name != 'english' and self.field.name != 'foreign': self.valueLabel.setAlignment(QtCore.Qt.AlignLeft) else: self.valueLabel.setAlignment(QtCore.Qt.AlignCenter) self.layout.addWidget(self.valueLabel) def setVisible(self, visible): # don't show this field if it's not being used if (self.value == ''): visible = False if self.field.name != 'english' and self.field.name != 'foreign': self.labelLabel.setVisible(visible) self.valueLabel.setVisible(visible) def setValue(self, newValue): self.value = newValue self.valueLabel.setText(newValue) def refreshFont(self): self.valueLabel.setFont(self.field.vocab.fonts[self.field.font]) class FieldMetaEdit(QtCore.QObject): def __init__(self, field, grid, parent = None): QtCore.QObject.__init__(self, parent) self.field = field self.deleteMe = False self.labelEdit = QtGui.QLineEdit(self.field.label) self.deleteButton = QtGui.QPushButton('delete') #FIXME put a 'trash can' icon on this button if self.field.name == 'chapter' or self.field.name == 'difficulty' or self.field.name == 'english' or self.field.name == 'foreign': # some fields should be undeletable self.deleteButton.setEnabled(False) self.selectPosition = QtGui.QComboBox() for position in fieldPositionLabel: self.selectPosition.addItem(position) if fieldPositionLabel[position] == self.field.position: self.selectPosition.setCurrentIndex(self.selectPosition.count()-1) self.selectShow = QtGui.QComboBox() for show in fieldShowLabel: self.selectShow.addItem(show) if fieldShowLabel[show] == self.field.show: self.selectShow.setCurrentIndex(self.selectShow.count()-1) self.selectFont = QtGui.QComboBox() for font in self.field.vocab.fonts: self.selectFont.addItem(font) if font == self.field.font: self.selectFont.setCurrentIndex(self.selectFont.count()-1) row = grid.rowCount() grid.addWidget(self.deleteButton, row, 0) grid.addWidget(QtGui.QLabel(self.field.name), row, 1) grid.addWidget(self.labelEdit, row, 2) grid.addWidget(self.selectPosition, row, 3) grid.addWidget(self.selectShow, row, 4) grid.addWidget(self.selectFont, row, 5) self.connect(self.deleteButton, QtCore.SIGNAL('clicked()'), self.delete) def delete(self): if self.deleteMe: self.deleteMe = False self.deleteButton.setText('delete') self.labelEdit.setEnabled(True) self.selectPosition.setEnabled(True) self.selectShow.setEnabled(True) self.selectFont.setEnabled(True) else: self.deleteMe = True self.deleteButton.setText('undelete') self.labelEdit.setEnabled(False) self.selectPosition.setEnabled(False) self.selectShow.setEnabled(False) self.selectFont.setEnabled(False) class FieldPosition: unknown = 0 # these are prefix and postfix onto the foreign language word PREFIX = 1 POSTFIX = 2 #FIXME should I allow prefix and postfix on the home language word? # TOP = 3 # BOTTOM = 4 LEFT = 5 RIGHT = 6 CENTRE = 7 fieldPositionLabel = {} fieldPositionLabel['Prefix'] = FieldPosition.PREFIX fieldPositionLabel['Postfix'] = FieldPosition.POSTFIX fieldPositionLabel['Top-Left'] = FieldPosition.LEFT fieldPositionLabel['Top-Right'] = FieldPosition.RIGHT fieldPositionLabel['Centre'] = FieldPosition.CENTRE fieldAlignment = {} fieldAlignment[FieldPosition.LEFT] = QtCore.Qt.AlignLeft fieldAlignment[FieldPosition.RIGHT] = QtCore.Qt.AlignRight fieldAlignment[FieldPosition.CENTRE] = QtCore.Qt.AlignCenter class FieldShow: ALWAYS = 0 ONHINT = 1 ONREVEAL = 2 NEVER = 3 fieldShowLabel = {} fieldShowLabel['Always'] = FieldShow.ALWAYS fieldShowLabel['On Hint'] = FieldShow.ONHINT fieldShowLabel['On Reveal'] = FieldShow.ONREVEAL fieldShowLabel['Never'] = FieldShow.NEVER
Python
# flashcard.py # this is the class for each card. import sys import string import exceptions from PyQt4 import QtGui, QtCore from wordtype import * class FileFormatError(exceptions.Exception): def __init__(self, message = 'The file is not correctly formatted!'): self.message = message return def flashCardFromCSV(vocab, parent, values): if len(values) == 0: raise FileFormatError('No card data') wordtype = values.pop(0) if wordtype == '': raise FileFormatError('Empty word type!') # make sure that values is the right length length = len(vocab.wordtypes[wordtype].fields) #print wordtype, length while len(values) < length: values.append('') while len(values) > length: values.pop() return FlashCard(vocab, parent, wordtype, valuesToDict(values, vocab.wordtypes[wordtype].fields)) #def copyFlashCard(card): # return FlashCard(card.vocab, card.parent, card.wordType.name, card.values) def valuesToDict(values, fields): # change array of values for a card into a dictionary # with fieldnames as keys # values must be the right amount in the right order assert(len(fields) == len(values)) valuesDict = {} for i in range(len(fields)): valuesDict[fields[i].name] = values[i] return valuesDict class FlashCard(QtGui.QWidget): def __init__(self, vocab, parent, wordtype, values): QtGui.QWidget.__init__(self, parent) self.parent = parent self.vocab = vocab self.wordType = self.vocab.wordtypes[wordtype] self.values = values # make sure there's a value for each field for field in self.wordType.fields: if not field.name in self.values: self.values[field.name] = '' assert(len(self.values) >= len(self.wordType.fields)) self.fieldInstances = {} self.fieldIndices = {} self.guiArea = {} self.mainLayout = QtGui.QGridLayout(self) def doLayout(self): if not len(self.guiArea) > 0: # if we have already done the layout don't do it again #self.mainLayout = QtGui.QGridLayout() self.guiArea[FieldPosition.LEFT] = QtGui.QVBoxLayout() self.guiArea[FieldPosition.RIGHT] = QtGui.QVBoxLayout() self.guiArea[FieldPosition.CENTRE] = QtGui.QVBoxLayout() homePreString = '' foreignPreString = '' homePostString = '' foreignPostString = '' for i in range(len(self.wordType.fields)): fieldName = self.wordType.fields[i].name if not fieldName in self.values.keys(): self.values[fieldName] = '' if self.wordType.fields[i].position == FieldPosition.PREFIX: #if str(self.wordType.fields[i].font.family()) == str(self.vocab.fontName): foreignPreString = foreignPreString + self.values[fieldName] + ' ' #else: # homePreString = homePreString + self.values[fieldName] + ' ' elif self.wordType.fields[i].position == FieldPosition.POSTFIX: # if self.wordType.fields[i].font.family().compare(self.vocab.foreignFontBig.family()) == 0: foreignPostString = foreignPostString + ' ' + self.values[fieldName] #else: # homePostString = homePostString + ' ' + self.values[fieldName] else: self.fieldIndices[fieldName] = i if fieldName != 'english' and fieldName != 'foreign': fieldInst = self.wordType.fields[i].instantiate(self.values[fieldName], self) self.fieldInstances[fieldName] = fieldInst self.guiArea[fieldInst.field.position].insertLayout(-1, fieldInst.layout) englishFull = homePreString + self.values['english'] + homePostString self.fieldInstances['english'] = self.wordType.fields[self.fieldIndices['english']].instantiate(englishFull, self) self.guiArea[FieldPosition.CENTRE].insertLayout(0, self.fieldInstances['english'].layout) foreignFull = foreignPreString + self.values['foreign'] + foreignPostString self.fieldInstances['foreign'] = self.wordType.fields[self.fieldIndices['foreign']].instantiate(foreignFull, self) self.guiArea[FieldPosition.CENTRE].insertLayout(0, self.fieldInstances['foreign'].layout) self.mainLayout.addLayout(self.guiArea[FieldPosition.LEFT], 0, 0, QtCore.Qt.AlignLeft) self.mainLayout.addLayout(self.guiArea[FieldPosition.RIGHT], 0, 1, QtCore.Qt.AlignRight) self.mainLayout.addLayout(self.guiArea[FieldPosition.CENTRE], 1, 0, 1, -1, QtCore.Qt.AlignCenter) #self.setLayout(self.mainLayout) self.reset() def redoLayout(self): if len(self.guiArea) > 0: for field in self.fieldInstances: self.fieldInstances[field].layout.setParent(None) self.fieldInstances[field].setVisible(False) for key in self.guiArea: self.guiArea[key].setParent(None) del self.fieldInstances del self.fieldIndices del self.guiArea self.fieldInstances = {} self.fieldIndices = {} self.guiArea = {} #self.setLayout(None) #self.mainLayout = None self.doLayout() def show(self, visible, fieldType): for key in self.fieldInstances: if self.fieldInstances[key].field.show == fieldType and self.fieldInstances[key].field.position != FieldPosition.PREFIX and self.fieldInstances[key].field.position != FieldPosition.POSTFIX: self.fieldInstances[key].setVisible(visible) def reset(self): self.show(True, FieldShow.ALWAYS) self.show(False, FieldShow.ONHINT) self.show(False, FieldShow.ONREVEAL) self.show(False, FieldShow.NEVER) def refreshFonts(self): if len(self.guiArea) > 0: for field in self.fieldInstances: self.fieldInstances[field].refreshFont() def changeDifficulty(self, inc): self.values['difficulty'] = str(float(self.values['difficulty']) + inc) self.fieldInstances['difficulty'].setValue(str(self.values['difficulty'])) self.vocab.changed = True def toCSV(self, csvWriter): """write CSV that defines this card""" row = [self.wordType.name] # The order of values must be the same as the order of fields in the list of fields in the wordtype object # as this is how values are matched to fields when the card is read from csv for i in range(len(self.wordType.fields)): if self.wordType.fields[i].name in self.values.keys(): row.append((self.values[self.wordType.fields[i].name])) else: row.append('') csvWriter.writerow(row) def writeXML(self, xmlWriter): """write XML that defines this card""" xmlWriter.writeStartElement('flashCard') xmlWriter.writeAttribute('type', self.wordType.name) # only save values that belong to a field for field in self.wordType.fields: # don't bother saving empty values if str(field.name) in self.values and (not self.values[str(field.name)] == ''): xmlWriter.writeTextElement(field.name, self.values[str(field.name)]) xmlWriter.writeEndElement() def copy(self): valuesCopy = {} for key in self.values: valuesCopy[key] = self.values[key] return FlashCard(self.vocab, self.parent, self.wordType.name, valuesCopy)
Python
# constants.py # constnt to share between multiple files flashblack_version = 'flashblack 0.3'
Python
#!/usr/bin/python # flasblack.py # launches the flashblack application global flashblack_version flashblack_version = 'flashblack 0.3' import sys from PyQt4 import QtGui, QtCore from flashcardgui import FlashCardGui app = QtGui.QApplication(sys.argv) flashcards = FlashCardGui() flashcards.show() sys.exit(app.exec_())
Python
#!/usr/bin/python # flashcardgui.py # this is a PyQt gui for the greek flashcard program from PyQt4 import QtGui, QtCore from flashcard import FlashCard from vocab import Vocab from constants import flashblack_version class FlashCardGui(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.everythingLayout = QtGui.QVBoxLayout(self) self.vocab = Vocab(self) self.setGeometry(100, 100, 500, 300) self.setWindowTitle('Flashblack - Language Flash Card Application') self.menuBar = QtGui.QMenuBar(self) self.menuBar.setMinimumWidth(200) self.vocabMenu = self.menuBar.addMenu('Vocab') self.newVocabAction = QtGui.QAction(self) self.newVocabAction.setText('New') self.connect(self.newVocabAction, QtCore.SIGNAL('triggered()'), self.vocab.newVocab) self.vocabMenu.addAction(self.newVocabAction) self.loadVocabAction = QtGui.QAction(self) self.loadVocabAction.setText('Open...') self.connect(self.loadVocabAction, QtCore.SIGNAL('triggered()'), self.vocab.loadVocab) self.vocabMenu.addAction(self.loadVocabAction) self.saveVocabAction = QtGui.QAction(self) self.saveVocabAction.setText('Save') self.saveVocabAction.setEnabled(False) self.connect(self.saveVocabAction, QtCore.SIGNAL('triggered()'), self.vocab.saveVocab) self.vocabMenu.addAction(self.saveVocabAction) self.saveVocabAsAction = QtGui.QAction(self) self.saveVocabAsAction.setText('Save As...') self.saveVocabAsAction.setEnabled(False) self.connect(self.saveVocabAsAction, QtCore.SIGNAL('triggered()'), self.vocab.saveVocabAs) self.vocabMenu.addAction(self.saveVocabAsAction) self.editWordTypesAction = QtGui.QAction(self) self.editWordTypesAction.setText('Edit Word Types...') self.editWordTypesAction.setEnabled(False) self.connect(self.editWordTypesAction, QtCore.SIGNAL('triggered()'), self.vocab.editWordTypes) self.vocabMenu.addAction(self.editWordTypesAction) self.editFontsAction = QtGui.QAction(self) self.editFontsAction.setText('Edit Fonts...') self.editFontsAction.setEnabled(False) self.connect(self.editFontsAction, QtCore.SIGNAL('triggered()'), self.vocab.editFonts) self.vocabMenu.addAction(self.editFontsAction) self.editDifficultyAction = QtGui.QAction(self) self.editDifficultyAction.setText('Edit Change in Difficulty...') self.editDifficultyAction.setEnabled(False) self.connect(self.editDifficultyAction, QtCore.SIGNAL('triggered()'), self.vocab.editDifficultyChange) self.vocabMenu.addAction(self.editDifficultyAction) self.cardsMenu = self.menuBar.addMenu('Card') self.cardsMenu.setEnabled(False) self.editCurrentAction = QtGui.QAction(self) self.editCurrentAction.setText('Edit...') self.editCurrentAction.setEnabled(False) self.connect(self.editCurrentAction, QtCore.SIGNAL('triggered()'), self.vocab.editCurrentCard) self.cardsMenu.addAction(self.editCurrentAction) self.dupCurrentAction = QtGui.QAction(self) self.dupCurrentAction.setText('Duplicate') self.dupCurrentAction.setEnabled(False) self.connect(self.dupCurrentAction, QtCore.SIGNAL('triggered()'), self.vocab.duplicateCurrentCard) self.cardsMenu.addAction(self.dupCurrentAction) self.newCardAction = QtGui.QAction(self) self.newCardAction.setText('New...') self.connect(self.newCardAction, QtCore.SIGNAL('triggered()'), self.vocab.newCard) self.cardsMenu.addAction(self.newCardAction) self.deleteCardAction = QtGui.QAction(self) self.deleteCardAction.setText('Delete') self.deleteCardAction.setEnabled(False) self.connect(self.deleteCardAction, QtCore.SIGNAL('triggered()'), self.vocab.deleteCurrentCard) self.cardsMenu.addAction(self.deleteCardAction) self.toolsMenu = self.menuBar.addMenu('Tools') self.toolsMenu.setEnabled(False) self.selectActiveAction = QtGui.QAction(self) self.selectActiveAction.setText('Select Active Cards...') self.connect(self.selectActiveAction, QtCore.SIGNAL('triggered()'), self.vocab.selectActiveCards) self.toolsMenu.addAction(self.selectActiveAction) self.shuffleActiveAction = QtGui.QAction(self) self.shuffleActiveAction.setText('Shuffle Active Cards') self.shuffleActiveAction.setEnabled(False) self.connect(self.shuffleActiveAction, QtCore.SIGNAL('triggered()'), self.vocab.shuffleActiveCards) self.toolsMenu.addAction(self.shuffleActiveAction) self.helpMenu = self.menuBar.addMenu('Help') self.aboutAction = QtGui.QAction(self) self.aboutAction.setText('About') self.connect(self.aboutAction, QtCore.SIGNAL('triggered()'), self.about) self.helpMenu.addAction(self.aboutAction) self.everythingLayout.addStretch() self.everythingLayout.addWidget(self.vocab.activeCards) self.everythingLayout.addWidget(self.vocab.progress) self.everythingLayout.addStretch() self.buttonPanel = QtGui.QHBoxLayout() self.previousButton = QtGui.QPushButton('Previous', self) self.revealButton = QtGui.QPushButton('Reveal', self) self.wrongButton = QtGui.QPushButton('I got it wrong', self) self.rightButton = QtGui.QPushButton('I got it right', self) self.hintButton = QtGui.QPushButton('Hint', self) self.nextButton = QtGui.QPushButton('Next', self) self.buttonPanel.addWidget(self.previousButton) self.buttonPanel.addWidget(self.revealButton) self.buttonPanel.addWidget(self.wrongButton) self.buttonPanel.addWidget(self.rightButton) self.buttonPanel.addWidget(self.hintButton) self.buttonPanel.addWidget(self.nextButton) self.setButtonsEnabled(False) self.everythingLayout.addLayout(self.buttonPanel) self.connect(self.revealButton, QtCore.SIGNAL('clicked()'), self.vocab.revealCurrentCard) self.connect(self.hintButton, QtCore.SIGNAL('clicked()'), self.vocab.revealCurrentCardHint) self.connect(self.nextButton, QtCore.SIGNAL('clicked()'), self.vocab.nextCard) self.connect(self.previousButton, QtCore.SIGNAL('clicked()'), self.vocab.previousCard) self.connect(self.wrongButton, QtCore.SIGNAL('clicked()'), self.vocab.gotItWrong) self.connect(self.rightButton, QtCore.SIGNAL('clicked()'), self.vocab.gotItRight) def about(self): QtGui.QMessageBox.about(self, 'About Flashblack', flashblack_version + "\nhttp://code.google.com/p/flashblack/") def keyPressEvent(self, event): key = event.key() if key == QtCore.Qt.Key_Comma and self.previousButton.isEnabled(): self.vocab.previousCard() if key == QtCore.Qt.Key_Period and self.nextButton.isEnabled(): self.vocab.nextCard() if key == QtCore.Qt.Key_Minus and self.wrongButton.isEnabled(): self.vocab.gotItWrong() if (key == QtCore.Qt.Key_Plus or key == QtCore.Qt.Key_Equal) and self.rightButton.isEnabled(): self.vocab.gotItRight() if key == QtCore.Qt.Key_0 and self.revealButton.isEnabled(): self.vocab.revealCurrentCard() else: QtGui.QWidget.keyPressEvent(self, event) def closeEvent(self, event): if self.vocab.changed: reply = QtGui.QMessageBox.warning(self, 'Vocab has been changed', "Would you like to save your changes to the vocab?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No, QtGui.QMessageBox.Cancel) if reply == QtGui.QMessageBox.Yes: self.vocab.saveVocab() event.accept() elif reply == QtGui.QMessageBox.No: event.accept() else: event.ignore() def setButtonsEnabled(self, enable = True): self.revealButton.setEnabled(enable) self.hintButton.setEnabled(enable) self.nextButton.setEnabled(enable) self.previousButton.setEnabled(enable) self.wrongButton.setEnabled(enable) self.rightButton.setEnabled(enable) def setVocabActionsEnabled(self, enable = True): self.saveVocabAction.setEnabled(enable) self.saveVocabAsAction.setEnabled(enable) self.editWordTypesAction.setEnabled(enable) self.editFontsAction.setEnabled(enable) self.editDifficultyAction.setEnabled(enable) self.cardsMenu.setEnabled(enable) self.toolsMenu.setEnabled(enable) def setCardActionsEnabled(self, enable = True): self.shuffleActiveAction.setEnabled(enable) self.editCurrentAction.setEnabled(enable) self.dupCurrentAction.setEnabled(enable) self.deleteCardAction.setEnabled(enable)
Python
# vocab.py # this is the class for a collection of flash cards from PyQt4 import QtGui, QtXml, QtCore # QXmlStreamWriter might be in QtXml or QtCore so import all from both and don't specify module from PyQt4.QtXml import * from PyQt4.QtCore import * import random, pdb, codecs, csv from constants import flashblack_version from flashcard import * from activecarddialog import * from editcarddialog import * from wordtypedialog import * from editfontsdialog import * from configdialog import * from wordtype import * from unicodecsv import * from user import home class Vocab: def __init__(self, parent=None): self.mainGui = parent self.filename = '' self.fonts = {} self.changed = False self.difficultyInc = 3 self.difficultyDec = -1 self.defaultCardValues = {'chapter': '1', 'difficulty': '50', 'foreign': 'Phrase', 'english': 'Translation'} self.wordtypes = {} self.cards = [] self.activeCards = QtGui.QStackedWidget(self.mainGui) self.progress = QtGui.QProgressBar(self.mainGui) self.progress.hide() self.dialog = None # just to keep a reference to the most recently active dialog self.activeCardFilter = None # create a singleton reference (per vocab) so we don't have to keep rebuiling this dialog and it remembers its state self.activeCardDialogSingleton = None def unset(self): self.filename = '' del self.fonts del self.wordtypes if self.activeCards.count() > 0: # hide current card, otherwise it still shows after we've removed it self.activeCards.currentWidget().reset() self.activeCards.currentWidget().show(False, FieldShow.ALWAYS) for card in self.cards: if self.isActive(card): self.activeCards.removeWidget(card) del self.cards self.progress.hide() self.activeCardDialogSingleton = None self.fonts = {} self.wordtypes = {} self.cards = [] def newVocab(self): if self.changed: reply = QtGui.QMessageBox.warning(self.mainGui, 'Vocab has been changed', "Would you like to save your changes to the vocab?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No, QtGui.QMessageBox.Cancel) if reply == QtGui.QMessageBox.Yes: self.saveVocab() elif reply == QtGui.QMessageBox.No: pass else: return self.unset() self.activeCardFilter = CardFilter({}, {}, [], True) # all cards active to begin with # provide 2 fonts to start with self.fonts['standard'] = QtGui.QFont() self.fonts['big'] = QtGui.QFont() self.fonts['big'].setPointSize(30) # provide a noun wordtype to start with fields = [] fields.append(Field(self, 'chapter', 'Chapter', 'standard', FieldPosition.LEFT, FieldShow.ALWAYS)) fields.append(Field(self, 'difficulty', 'Difficulty', 'standard', FieldPosition.RIGHT, FieldShow.ALWAYS)) fields.append(Field(self, 'foreign', 'Foreign word', 'big', FieldPosition.CENTRE, FieldShow.ALWAYS)) fields.append(Field(self, 'english', 'Translation', 'big', FieldPosition.CENTRE, FieldShow.ONREVEAL)) fields.append(Field(self, 'hint', 'Hint', 'standard', FieldPosition.CENTRE, FieldShow.ONHINT)) self.wordtypes['noun'] = WordType(self, 'noun', fields) self.mainGui.setVocabActionsEnabled(True) self.mainGui.setCardActionsEnabled(False) self.mainGui.setButtonsEnabled(False) QtGui.QMessageBox.information(self.mainGui, 'New Vocab', 'A new Vocab has been created. It does not yet contain any cards.') def setActiveCards(self): if self.activeCardFilter == None: self.selectActiveCards() return # get rid of current active cards self.mainGui.everythingLayout.removeWidget(self.activeCards) self.activeCards.hide() self.activeCards = QtGui.QStackedWidget(self.mainGui) self.mainGui.everythingLayout.insertWidget(1, self.activeCards) for card in self.cards: self.checkFilter(card) if self.activeCards.count(): self.progress.show() self.progress.setRange(0, self.activeCards.count()) self.progress.setValue(1) self.mainGui.setButtonsEnabled(True) self.mainGui.previousButton.setEnabled(False) self.mainGui.setCardActionsEnabled(True) else: QtGui.QMessageBox.information(self.mainGui, 'No Active Cards', 'No cards are in that range') self.mainGui.setButtonsEnabled(False) self.mainGui.setCardActionsEnabled(False) self.progress.hide() def checkFilter(self, card, index = None): if not self.activeCardFilter == None: if self.activeCardFilter.filterCard(card): if not self.isActive(card): card.doLayout() if index == None: self.activeCards.addWidget(card) else: self.activeCards.insertWidget(index, card) else: if self.isActive(card): self.activeCards.removeWidget(card) def isActive(self, card): if self.activeCards.count() == 0: return False for i in range(0, self.activeCards.count()): if card == self.activeCards.widget(i): return True return False def loadVocab(self, parent = None): """Load a vocab from a file.""" filter = "XML files (*.xml);;CSV files (*.csv);;All files (*)" loadFile = '' if self.filename == '': loadFile = QtGui.QFileDialog.getOpenFileName(self.mainGui, 'Open Vocab', home, filter) else: loadFile = QtGui.QFileDialog.getOpenFileName(self.mainGui, 'Open Vocab', self.filename, filter) if not (loadFile == ''): if self.changed: reply = QtGui.QMessageBox.warning(self.mainGui, 'Vocab has been changed', "Would you like to save your changes to the vocab?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No, QtGui.QMessageBox.Cancel) if reply == QtGui.QMessageBox.Yes: self.saveVocab() elif reply == QtGui.QMessageBox.No: pass else: return self.unset() self.filename = loadFile if self.filename.toLower().endsWith('.csv'): self.loadVocabCSV(parent) else: self.loadVocabXML() self.changed = False self.mainGui.setVocabActionsEnabled(True) self.selectActiveCards() def loadVocabCSV(self, parent): try: csvfile = codecs.open(self.filename, encoding='utf-8', mode='r') #file = open(self.filename, 'r') firstLine = csvfile.readline() csvReader = None if firstLine.startswith('"flashblack') or firstLine.startswith('flashblack'): # we are delaing with version 3.0 or later. Default dialect is used. csvReader = unicode_csv_reader(csvfile) else: try: csv.Sniffer().sniff(csvfile.read(1024)) # if we didn't get an exception that means there's quotes around the strings # we can't use the dialect that the sniffer returns because it produces a strane and inexplicable error csvReader = unicode_csv_reader(csvfile, delimiter=';', quotechar='"', skipinitialspace=True) csvfile.seek(0) except csv.Error, e: # however if the sniffer does raise an execption, it means there are no quotes csvReader = unicode_csv_reader(csvfile, delimiter=';', quoting=csv.QUOTE_NONE, skipinitialspace=True) csvfile.seek(0) rows = [] try: self.difficultyInc = float(csvReader.next()[0]) self.difficultyDec = float(csvReader.next()[0]) for row in csvReader: rows.append(row) except csv.Error, e: sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) csvfile.close() self.readFontsCSV(rows) self.readWordTypesCSV(rows) self.cards = [] for row in rows: try: self.cards.append(flashCardFromCSV(self, parent, row)) except FileFormatError, e: print e.message except IOError, e: QtGui.QMessageBox.critical(self.mainGui, "Unable to Load", "Could not load the vocab file.\n" + e.__repr__()) def readFontsCSV(self, input): if not input[0][0].startswith('font data'): return self.fonts = {} input.pop(0) while not input[0][0].startswith('/font data'): font = QtGui.QFont() font.fromString(input[0][1]) self.fonts[input[0][0]] = font input.pop(0) input.pop(0) # '/font data' def readWordTypesCSV(self, input): if not input[0][0].startswith('word-type data'): return self.wordtypes = {} input.pop(0) while not input[0][0].startswith('/word-type data'): typeName = input[0][0] self.wordtypes[typeName] = WordType(self, typeName, list()) input.pop(0) while not input[0][0].startswith('/' + typeName): #print typeName self.wordtypes[typeName].fields.append(Field(self, input[0][0], input[0][1], input[0][2], int(input[0][3]), int(input[0][4]))) input.pop(0) input.pop(0) # '/typename' input.pop(0) # '/word-type data' # print len(self.wordtypes['noun'].fields) def loadVocabXML(self): try: xmlFile = QtCore.QFile(self.filename) xmlFile.open(QtCore.QIODevice.ReadOnly) xmlFileRead = QtXml.QXmlInputSource(xmlFile) xmlReader = QtXml.QXmlSimpleReader() xmlHandler = VocabXmlHandler(self) xmlReader.setContentHandler(xmlHandler) xmlReader.setErrorHandler(xmlHandler) xmlReader.parse(xmlFileRead) except IOError, e: QtGui.QMessageBox.critical(self.mainGui, "Unable to Load", "Could not load the vocab file.\n" + e.__repr__()) def saveVocab(self): if self.filename == '': self.saveVocabAs() else: if self.filename.toLower().endsWith('.csv'): self.saveVocabCSV() elif self.filename.toLower().endsWith('.xml'): self.saveVocabXML() else: self.filename = self.filename + '.xml' self.saveVocabXML() def saveVocabAs(self): """Save this vocab into a file. Creates a xml or csv file storing details of the wordtypes and the flashcards contained by this vocab.""" filter = "XML file (*.xml);;CSV file (*.csv)" if self.filename == '': self.filename = QtGui.QFileDialog.getSaveFileName(self.mainGui, 'Save Vocab', home, filter) else: self.filename = QtGui.QFileDialog.getSaveFileName(self.mainGui, 'Save Vocab', self.filename, filter) if self.filename != '': self.saveVocab() def saveVocabCSV(self): try: outFile = codecs.open(self.filename, mode='wb') #outFile = codecs.open(self.filename, encoding='utf-8', mode='wb') csvWriter = UnicodeWriter(outFile) csvWriter.writerow([flashblack_version]) csvWriter.writerow([str(self.difficultyInc)]) csvWriter.writerow([str(self.difficultyDec)]) # output font data csvWriter.writerow(['font data']) for key in self.fonts: csvWriter.writerow([key, str(self.fonts[key].toString())]) csvWriter.writerow(['/font data']) # write out the word type data csvWriter.writerow(['word-type data']) for key in self.wordtypes: self.wordtypes[key].toCSV(csvWriter) csvWriter.writerow(['/word-type data']) # then write out the card data for card in self.cards: card.toCSV(csvWriter) outFile.close() self.changed = False except IOError, e: QtGui.QMessageBox.critical(self.mainGui, "Unable to Save", "Could not save the vocab file.\n" + e.__repr__()) def saveVocabXML(self): try: xmlFile = QtCore.QFile(self.filename) xmlFile.open(QtCore.QIODevice.WriteOnly) xmlWriter = QXmlStreamWriter(xmlFile) xmlWriter.setAutoFormatting(True) xmlWriter.writeStartDocument() xmlWriter.writeStartElement('vocab') #xmlWriter.writeTextElement('languageName', self.languageName) xmlWriter.writeTextElement('difficulty_increment', str(self.difficultyInc)) xmlWriter.writeTextElement('difficulty_decrement', str(self.difficultyDec)) xmlWriter.writeStartElement('fonts') for key in self.fonts: xmlWriter.writeStartElement('font') xmlWriter.writeAttribute('name', key) xmlWriter.writeCharacters(self.fonts[key].toString()) xmlWriter.writeEndElement() xmlWriter.writeEndElement() xmlWriter.writeStartElement('wordTypes') for key in self.wordtypes: self.wordtypes[key].writeXML(xmlWriter) xmlWriter.writeEndElement() xmlWriter.writeStartElement('flashCards') for card in self.cards: card.writeXML(xmlWriter) xmlWriter.writeEndElement() xmlWriter.writeEndElement() xmlWriter.writeEndDocument() self.changed = False except IOError, e: QtGui.QMessageBox.critical(self.mainGui, "Unable to Save", "Could not save the vocab file.\n" + e.__repr__()) def editWordTypes(self): self.dialog = WordTypeDialog(self, self.mainGui) self.dialog.show() def editFonts(self): self.dialog = EditFontsDialog(self, self.mainGui) self.dialog.show() def editDifficultyChange(self): self.dialog = ConfigDialog(self, self.mainGui) self.dialog.show() def revealCurrentCard(self): self.activeCards.currentWidget().show(True, FieldShow.ONREVEAL) self.mainGui.revealButton.setEnabled(False) # also reavel hint self.revealCurrentCardHint() def revealCurrentCardHint(self): self.activeCards.currentWidget().show(True, FieldShow.ONHINT) self.mainGui.hintButton.setEnabled(False) def nextCard(self): self.resetCurrentCard() self.activeCards.setCurrentIndex(self.activeCards.currentIndex() + 1) self.progress.setValue(self.progress.value() + 1) self.mainGui.previousButton.setEnabled(True) if self.progress.value() >= self.progress.maximum(): self.mainGui.nextButton.setEnabled(False) def previousCard(self): self.resetCurrentCard() self.activeCards.setCurrentIndex(self.activeCards.currentIndex() - 1) self.progress.setValue(self.progress.value() - 1) self.mainGui.nextButton.setEnabled(True) if self.progress.value() <= 1: self.mainGui.previousButton.setEnabled(False) def resetCurrentCard(self): self.activeCards.currentWidget().reset() self.mainGui.revealButton.setEnabled(True) self.mainGui.hintButton.setEnabled(True) def gotItRight(self): self.activeCards.currentWidget().changeDifficulty(self.difficultyDec) self.nextCard() def gotItWrong(self): self.activeCards.currentWidget().changeDifficulty(self.difficultyInc) self.nextCard() def selectActiveCards(self): if self.activeCardDialogSingleton == None: self.activeCardDialogSingleton = ActiveCardDialog(self, self.mainGui) self.dialog = self.activeCardDialogSingleton self.dialog.show() def shuffleActiveCards(self): self.resetCurrentCard() cards = [] self.progress.setValue(1) for i in range(0, self.activeCards.count()-1): cards.append(self.activeCards.currentWidget()) self.activeCards.removeWidget(cards[i]) random.shuffle(cards) for card in cards: self.activeCards.addWidget(card) def editCurrentCard(self): card = self.activeCards.currentWidget() self.dialog = EditCardDialog(card, self.mainGui) self.dialog.show() def newCard(self, card = None): if (card == None and self.activeCards.count()): card = self.activeCards.currentWidget() self.dialog = NewCardDialog(self, card, self.mainGui) self.dialog.show() def cardChanged(self, card): if self.isActive(card): activeIndex = self.activeCards.indexOf(card) self.checkFilter(card, activeIndex) else: self.checkFilter(card) if self.isActive(card): self.activeCards.setCurrentWidget(card) self.resetCurrentCard() self.mainGui.setButtonsEnabled(True) self.progress.show() self.progress.setMaximum(self.activeCards.count()) if self.progress.value() <= 1: self.mainGui.previousButton.setEnabled(False) if self.progress.value() >= self.progress.maximum(): self.mainGui.nextButton.setEnabled(False) def deleteCurrentCard(self): card = self.activeCards.currentWidget() self.activeCards.removeWidget(card) self.progress.setMaximum(self.activeCards.count()) self.cards.remove(card) def replaceCard(self, card, replacement): activeIndex = None if self.isActive(card): activeIndex = self.activeCards.indexOf(card) self.activeCards.removeWidget(card) i = self.cards.index(card) self.cards.remove(card) self.cards.insert(i, replacement) self.checkFilter(replacement, activeIndex) def duplicateCard(self, card): dup = card.copy() self.cards.insert(self.activeCards.currentIndex(), dup) if self.isActive(card): activeIndex = self.activeCards.indexOf(card) self.activeCards.insertWidget(activeIndex + 1, dup) dup.doLayout() self.progress.setRange(0, self.progress.maximum() + 1) self.changed = True def duplicateCurrentCard(self): self.duplicateCard(self.activeCards.currentWidget()) def refreshAllCards(self): # for each card that has been laid out replace it with a copy of itself so it redoes the layout. for card in self.cards: if len(card.guiArea) > 0: newCard = card.copy() if self.isActive(card): self.activeCards.removeWidget(card) card.setParent(None) i = self.cards.index(card) self.cards.remove(card) self.cards.insert(i, newCard) self.setActiveCards() def refreshFonts(self): for card in self.cards: card.refreshFonts() class VocabXmlHandler(QtXml.QXmlDefaultHandler): def __init__(self, vocab): QtXml.QXmlDefaultHandler.__init__(self) self.vocab = vocab def startDocument(self): self.elementStack = [] self.fontName = '' self.wordType = '' self.fieldName = '' self.cardType = '' self.justStarted = '' # this helps us know when we parse an element with no content return True def startElement(self, namespaceURI, localName, qName, attributes): self.elementStack.append(str(localName)) self.justStarted = str(localName) if localName == 'font': self.fontName = str(attributes.value('name')) if localName == 'wordType': self.wordType = str(attributes.value('name')) self.wordTypeData = [] if localName == 'field': self.fieldName = str(attributes.value('name')) self.fieldData = {} if localName == 'flashCard': self.cardType = str(attributes.value('type')) self.cardData = {} return True def endElement(self, namespaceURI, localName, qName): if self.justStarted == str(localName): # we have an element with no content. Need to call the characters method with an empty string self.characters('') self.justStarted = '' self.elementStack.pop() if localName == 'field': # FIXME: should probably check that all the values for a field have been collected self.wordTypeData.append(Field(self.vocab, self.fieldName, self.fieldData['label'], self.fieldData['font'], self.fieldData['position'], self.fieldData['show'])) elif localName == 'wordType': self.vocab.wordtypes[self.wordType] = WordType(self.vocab, self.wordType, self.wordTypeData) elif localName == 'flashCard': self.vocab.cards.append(FlashCard(self.vocab, self.vocab.mainGui, self.cardType, self.cardData)) return True def characters(self, content): self.justStarted = '' if self.elementStack[len(self.elementStack) - 2] == 'vocab': #if self.elementStack[len(self.elementStack) - 1] == 'languageName': # self.vocab.languageName = str(content) if self.elementStack[len(self.elementStack) - 1] == 'difficulty_increment': self.vocab.difficultyInc = float(content) if self.elementStack[len(self.elementStack) - 1] == 'difficulty_decrement': self.vocab.difficultyDec = float(content) elif self.elementStack[len(self.elementStack) - 2] == 'fonts': font = QtGui.QFont() font.fromString(content) #FIXME: should do something sensible if font is not recognised self.vocab.fonts[self.fontName] = font elif self.elementStack[len(self.elementStack) - 2] == 'field': self.fieldData[self.elementStack[len(self.elementStack) - 1]] = unicode(content) elif self.elementStack[len(self.elementStack) - 2] == 'flashCard': self.cardData[self.elementStack[len(self.elementStack) - 1]] = unicode(content) return True
Python
# configdialog.py # this is a dialog to allow the user to specify the change in difficulty of a card when you get it wrong or right import sys from PyQt4 import QtGui, QtCore class ConfigDialog(QtGui.QDialog): def __init__(self, vocab, parent=None): QtGui.QDialog.__init__(self, parent) self.vocab = vocab self.setWindowTitle('Specify Change in Difficulty') self.layout = QtGui.QGridLayout(self) changeValidator = QtGui.QDoubleValidator(self) changeValidator.setBottom(0) self.increment = QtGui.QLineEdit(str(self.vocab.difficultyInc)) self.increment.setValidator(changeValidator) self.increment.setFixedWidth(40) self.decrement = QtGui.QLineEdit(str(self.vocab.difficultyDec * -1)) self.decrement.setValidator(changeValidator) self.decrement.setFixedWidth(40) self.layout.addWidget(QtGui.QLabel('When I click \'I got it wrong\' increase difficulty by', self), 0, 0, 1, 2) self.layout.addWidget(self.increment, 0, 2) self.layout.addWidget(QtGui.QLabel('When I click \'I got it right\' decrease difficulty by', self), 1, 0, 1, 2) self.layout.addWidget(self.decrement, 1, 2) self.okButton = QtGui.QPushButton('OK', self) self.cancelButton = QtGui.QPushButton('Cancel', self) row = self.layout.rowCount() self.layout.addWidget(self.okButton, row, 0) self.layout.addWidget(self.cancelButton, row, 1) self.connect(self.okButton, QtCore.SIGNAL('clicked()'), self.ok) self.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.cancel) def ok(self): self.vocab.difficultyInc = float(str(self.increment.text())) self.vocab.difficultyDec = -1 * float(str(self.decrement.text())) self.vocab.changed = True self.close() def cancel(self): self.close()
Python
#!/usr/bin/python # flashcardgui.py # this is a PyQt gui for the greek flashcard program from PyQt4 import QtGui, QtCore from flashcard import FlashCard from vocab import Vocab from constants import flashblack_version class FlashCardGui(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.everythingLayout = QtGui.QVBoxLayout(self) self.vocab = Vocab(self) self.setGeometry(100, 100, 500, 300) self.setWindowTitle('Flashblack - Language Flash Card Application') self.menuBar = QtGui.QMenuBar(self) self.menuBar.setMinimumWidth(200) self.vocabMenu = self.menuBar.addMenu('Vocab') self.newVocabAction = QtGui.QAction(self) self.newVocabAction.setText('New') self.connect(self.newVocabAction, QtCore.SIGNAL('triggered()'), self.vocab.newVocab) self.vocabMenu.addAction(self.newVocabAction) self.loadVocabAction = QtGui.QAction(self) self.loadVocabAction.setText('Open...') self.connect(self.loadVocabAction, QtCore.SIGNAL('triggered()'), self.vocab.loadVocab) self.vocabMenu.addAction(self.loadVocabAction) self.saveVocabAction = QtGui.QAction(self) self.saveVocabAction.setText('Save') self.saveVocabAction.setEnabled(False) self.connect(self.saveVocabAction, QtCore.SIGNAL('triggered()'), self.vocab.saveVocab) self.vocabMenu.addAction(self.saveVocabAction) self.saveVocabAsAction = QtGui.QAction(self) self.saveVocabAsAction.setText('Save As...') self.saveVocabAsAction.setEnabled(False) self.connect(self.saveVocabAsAction, QtCore.SIGNAL('triggered()'), self.vocab.saveVocabAs) self.vocabMenu.addAction(self.saveVocabAsAction) self.editWordTypesAction = QtGui.QAction(self) self.editWordTypesAction.setText('Edit Word Types...') self.editWordTypesAction.setEnabled(False) self.connect(self.editWordTypesAction, QtCore.SIGNAL('triggered()'), self.vocab.editWordTypes) self.vocabMenu.addAction(self.editWordTypesAction) self.editFontsAction = QtGui.QAction(self) self.editFontsAction.setText('Edit Fonts...') self.editFontsAction.setEnabled(False) self.connect(self.editFontsAction, QtCore.SIGNAL('triggered()'), self.vocab.editFonts) self.vocabMenu.addAction(self.editFontsAction) self.editDifficultyAction = QtGui.QAction(self) self.editDifficultyAction.setText('Edit Change in Difficulty...') self.editDifficultyAction.setEnabled(False) self.connect(self.editDifficultyAction, QtCore.SIGNAL('triggered()'), self.vocab.editDifficultyChange) self.vocabMenu.addAction(self.editDifficultyAction) self.cardsMenu = self.menuBar.addMenu('Card') self.cardsMenu.setEnabled(False) self.editCurrentAction = QtGui.QAction(self) self.editCurrentAction.setText('Edit...') self.editCurrentAction.setEnabled(False) self.connect(self.editCurrentAction, QtCore.SIGNAL('triggered()'), self.vocab.editCurrentCard) self.cardsMenu.addAction(self.editCurrentAction) self.dupCurrentAction = QtGui.QAction(self) self.dupCurrentAction.setText('Duplicate') self.dupCurrentAction.setEnabled(False) self.connect(self.dupCurrentAction, QtCore.SIGNAL('triggered()'), self.vocab.duplicateCurrentCard) self.cardsMenu.addAction(self.dupCurrentAction) self.newCardAction = QtGui.QAction(self) self.newCardAction.setText('New...') self.connect(self.newCardAction, QtCore.SIGNAL('triggered()'), self.vocab.newCard) self.cardsMenu.addAction(self.newCardAction) self.deleteCardAction = QtGui.QAction(self) self.deleteCardAction.setText('Delete') self.deleteCardAction.setEnabled(False) self.connect(self.deleteCardAction, QtCore.SIGNAL('triggered()'), self.vocab.deleteCurrentCard) self.cardsMenu.addAction(self.deleteCardAction) self.toolsMenu = self.menuBar.addMenu('Tools') self.toolsMenu.setEnabled(False) self.selectActiveAction = QtGui.QAction(self) self.selectActiveAction.setText('Select Active Cards...') self.connect(self.selectActiveAction, QtCore.SIGNAL('triggered()'), self.vocab.selectActiveCards) self.toolsMenu.addAction(self.selectActiveAction) self.shuffleActiveAction = QtGui.QAction(self) self.shuffleActiveAction.setText('Shuffle Active Cards') self.shuffleActiveAction.setEnabled(False) self.connect(self.shuffleActiveAction, QtCore.SIGNAL('triggered()'), self.vocab.shuffleActiveCards) self.toolsMenu.addAction(self.shuffleActiveAction) self.helpMenu = self.menuBar.addMenu('Help') self.aboutAction = QtGui.QAction(self) self.aboutAction.setText('About') self.connect(self.aboutAction, QtCore.SIGNAL('triggered()'), self.about) self.helpMenu.addAction(self.aboutAction) self.everythingLayout.addStretch() self.everythingLayout.addWidget(self.vocab.activeCards) self.everythingLayout.addWidget(self.vocab.progress) self.everythingLayout.addStretch() self.buttonPanel = QtGui.QHBoxLayout() self.previousButton = QtGui.QPushButton('Previous', self) self.revealButton = QtGui.QPushButton('Reveal', self) self.wrongButton = QtGui.QPushButton('I got it wrong', self) self.rightButton = QtGui.QPushButton('I got it right', self) self.hintButton = QtGui.QPushButton('Hint', self) self.nextButton = QtGui.QPushButton('Next', self) self.buttonPanel.addWidget(self.previousButton) self.buttonPanel.addWidget(self.revealButton) self.buttonPanel.addWidget(self.wrongButton) self.buttonPanel.addWidget(self.rightButton) self.buttonPanel.addWidget(self.hintButton) self.buttonPanel.addWidget(self.nextButton) self.setButtonsEnabled(False) self.everythingLayout.addLayout(self.buttonPanel) self.connect(self.revealButton, QtCore.SIGNAL('clicked()'), self.vocab.revealCurrentCard) self.connect(self.hintButton, QtCore.SIGNAL('clicked()'), self.vocab.revealCurrentCardHint) self.connect(self.nextButton, QtCore.SIGNAL('clicked()'), self.vocab.nextCard) self.connect(self.previousButton, QtCore.SIGNAL('clicked()'), self.vocab.previousCard) self.connect(self.wrongButton, QtCore.SIGNAL('clicked()'), self.vocab.gotItWrong) self.connect(self.rightButton, QtCore.SIGNAL('clicked()'), self.vocab.gotItRight) def about(self): QtGui.QMessageBox.about(self, 'About Flashblack', flashblack_version + "\nhttp://code.google.com/p/flashblack/") def keyPressEvent(self, event): key = event.key() if key == QtCore.Qt.Key_Comma and self.previousButton.isEnabled(): self.vocab.previousCard() if key == QtCore.Qt.Key_Period and self.nextButton.isEnabled(): self.vocab.nextCard() if key == QtCore.Qt.Key_Minus and self.wrongButton.isEnabled(): self.vocab.gotItWrong() if (key == QtCore.Qt.Key_Plus or key == QtCore.Qt.Key_Equal) and self.rightButton.isEnabled(): self.vocab.gotItRight() if key == QtCore.Qt.Key_0 and self.revealButton.isEnabled(): self.vocab.revealCurrentCard() else: QtGui.QWidget.keyPressEvent(self, event) def closeEvent(self, event): if self.vocab.changed: reply = QtGui.QMessageBox.warning(self, 'Vocab has been changed', "Would you like to save your changes to the vocab?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No, QtGui.QMessageBox.Cancel) if reply == QtGui.QMessageBox.Yes: self.vocab.saveVocab() event.accept() elif reply == QtGui.QMessageBox.No: event.accept() else: event.ignore() def setButtonsEnabled(self, enable = True): self.revealButton.setEnabled(enable) self.hintButton.setEnabled(enable) self.nextButton.setEnabled(enable) self.previousButton.setEnabled(enable) self.wrongButton.setEnabled(enable) self.rightButton.setEnabled(enable) def setVocabActionsEnabled(self, enable = True): self.saveVocabAction.setEnabled(enable) self.saveVocabAsAction.setEnabled(enable) self.editWordTypesAction.setEnabled(enable) self.editFontsAction.setEnabled(enable) self.editDifficultyAction.setEnabled(enable) self.cardsMenu.setEnabled(enable) self.toolsMenu.setEnabled(enable) def setCardActionsEnabled(self, enable = True): self.shuffleActiveAction.setEnabled(enable) self.editCurrentAction.setEnabled(enable) self.dupCurrentAction.setEnabled(enable) self.deleteCardAction.setEnabled(enable)
Python
#!/usr/bin/python # flasblack.py # launches the flashblack application global flashblack_version flashblack_version = 'flashblack 0.3' import sys from PyQt4 import QtGui, QtCore from flashcardgui import FlashCardGui app = QtGui.QApplication(sys.argv) flashcards = FlashCardGui() flashcards.show() sys.exit(app.exec_())
Python
# editfontsdialog.py # this is a dialog to allow the user to edit the fonts in a vocab. import sys from PyQt4 import QtGui, QtCore class EditFontsDialog(QtGui.QDialog): def __init__(self, vocab, parent = None): QtGui.QDialog.__init__(self, parent) self.vocab = vocab self.fontEdits = {} self.newFonts = {} self.setWindowTitle('Edit Fonts') self.layout = QtGui.QVBoxLayout(self) self.gridLayout = QtGui.QGridLayout() self.buttonPanelA = QtGui.QHBoxLayout() self.buttonPanelB = QtGui.QHBoxLayout() for fontName in self.vocab.fonts: fontEdit = fontEditWidget(fontName, self.vocab.fonts[fontName], self.gridLayout, self.vocab.mainGui) self.fontEdits[fontName] = fontEdit self.newFontButton = QtGui.QPushButton('New Font', self) self.okButton = QtGui.QPushButton('OK', self) self.cancelButton = QtGui.QPushButton('Cancel', self) self.buttonPanelA.addWidget(self.newFontButton) self.buttonPanelA.addStretch() self.buttonPanelB.addWidget(self.okButton) self.buttonPanelB.addWidget(self.cancelButton) self.buttonPanelB.addStretch() self.layout.addLayout(self.gridLayout) self.layout.addLayout(self.buttonPanelA) self.layout.addLayout(self.buttonPanelB) self.connect(self.newFontButton, QtCore.SIGNAL('clicked()'), self.newFont) self.connect(self.okButton, QtCore.SIGNAL('clicked()'), self.ok) self.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.cancel) def newFont(self): (ufontName, nameOK) = QtGui.QInputDialog.getText(self, 'New Font Name', 'Enter a name for the font') fontName = str(ufontName) if nameOK: if fontName in self.vocab.fonts.keys(): QtGui.QMessageBox.information(self, 'Choose a unique name', "There is already a font calle %s. Choose a unique name." % (fontName)) else: (newFont, fontOK) = QtGui.QFontDialog.getFont(QtGui.QFont(), None, 'Select new font') if fontOK: fontEdit = fontEditWidget(fontName, newFont, self.gridLayout, self.vocab.mainGui) self.fontEdits[fontName] = fontEdit self.newFonts[fontName] = newFont def ok(self): self.vocab.fonts.update(self.newFonts) for key in self.fontEdits: self.vocab.fonts[key] = self.fontEdits[key].font self.vocab.refreshFonts() self.vocab.changed = True self.close() def cancel(self): self.close() class fontEditWidget(QtCore.QObject): def __init__(self, fontName, font, grid, parent = None): QtCore.QObject.__init__(self, parent) self.fontName = fontName self.font = font self.fontShow = QtGui.QLabel(fontName) self.fontShow.setFont(self.font) # I don't think it's necessary for the user to be able to delete fonts #self.deleteButton = QtGui.QPushButton('Delete') self.editButton = QtGui.QPushButton('Edit') self.connect(self.editButton, QtCore.SIGNAL('clicked()'), self.selectFont) row = grid.rowCount() grid.addWidget(QtGui.QLabel(self.fontName), row, 0) grid.addWidget(self.fontShow, row, 1) grid.addWidget(self.editButton, row, 2) def selectFont(self): (newFont, ok) = QtGui.QFontDialog.getFont(self.font, None, 'Select new font') if ok: self.font = newFont self.fontShow.setFont(self.font)
Python
#!/usr/bin/python # Copyright 2011 Google, Inc. All Rights Reserved. # simple script to walk source tree looking for third-party licenses # dumps resulting html page to stdout import os, re, mimetypes, sys # read source directories to scan from command line SOURCE = sys.argv[1:] # regex to find /* */ style comment blocks COMMENT_BLOCK = re.compile(r"(/\*.+?\*/)", re.MULTILINE | re.DOTALL) # regex used to detect if comment block is a license COMMENT_LICENSE = re.compile(r"(license)", re.IGNORECASE) COMMENT_COPYRIGHT = re.compile(r"(copyright)", re.IGNORECASE) EXCLUDE_TYPES = [ "application/xml", "image/png", ] # list of known licenses; keys are derived by stripping all whitespace and # forcing to lowercase to help combine multiple files that have same license. KNOWN_LICENSES = {} class License: def __init__(self, license_text): self.license_text = license_text self.filenames = [] # add filename to the list of files that have the same license text def add_file(self, filename): if filename not in self.filenames: self.filenames.append(filename) LICENSE_KEY = re.compile(r"[^\w]") def find_license(license_text): # TODO(alice): a lot these licenses are almost identical Apache licenses. # Most of them differ in origin/modifications. Consider combining similar # licenses. license_key = LICENSE_KEY.sub("", license_text).lower() if license_key not in KNOWN_LICENSES: KNOWN_LICENSES[license_key] = License(license_text) return KNOWN_LICENSES[license_key] def discover_license(exact_path, filename): # when filename ends with LICENSE, assume applies to filename prefixed if filename.endswith("LICENSE"): with open(exact_path) as file: license_text = file.read() target_filename = filename[:-len("LICENSE")] if target_filename.endswith("."): target_filename = target_filename[:-1] find_license(license_text).add_file(target_filename) return None # try searching for license blocks in raw file mimetype = mimetypes.guess_type(filename) if mimetype in EXCLUDE_TYPES: return None with open(exact_path) as file: raw_file = file.read() # include comments that have both "license" and "copyright" in the text for comment in COMMENT_BLOCK.finditer(raw_file): comment = comment.group(1) if COMMENT_LICENSE.search(comment) is None: continue if COMMENT_COPYRIGHT.search(comment) is None: continue find_license(comment).add_file(filename) for source in SOURCE: for root, dirs, files in os.walk(source): for name in files: discover_license(os.path.join(root, name), name) print "<html><head><style> body { font-family: sans-serif; } pre { background-color: #eeeeee; padding: 1em; white-space: pre-wrap; } </style></head><body>" for license in KNOWN_LICENSES.values(): print "<h3>Notices for files:</h3><ul>" filenames = license.filenames filenames.sort() for filename in filenames: print "<li>%s</li>" % (filename) print "</ul>" print "<pre>%s</pre>" % license.license_text print "</body></html>"
Python
#!/usr/bin/env python # Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import os from StringIO import StringIO from PIL import Image import datauri def image_to_data_uri_(im): f = StringIO() im.save(f, 'PNG') uri = datauri.to_data_uri(f.getvalue(), 'foo.png') f.close() return uri def main(): src_im = Image.open(sys.argv[1]) template_params = {} template_params['id'] = sys.argv[1] template_params['image_uri'] = image_to_data_uri_(src_im) template_params['icon_uri'] = image_to_data_uri_(src_im) template_params['width'] = src_im.size[0] template_params['height'] = src_im.size[1] print open('res/shape_png_template.xml').read() % template_params if __name__ == '__main__': main()
Python
#!/usr/bin/env python # Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import base64 import sys import mimetypes def to_data_uri(data, file_name): '''Takes a file object and returns its data: string.''' mime_type = mimetypes.guess_type(file_name) return 'data:%(mimetype)s;base64,%(data)s' % dict(mimetype=mime_type[0], data=base64.b64encode(data)) def main(): print to_data_uri(open(sys.argv[1], 'rb').read(), sys.argv[1]) if __name__ == '__main__': main()
Python
#!/usr/bin/env python # Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import os from StringIO import StringIO from PIL import Image import datauri RGBA_BLACK = (0, 0, 0, 255) sign_ = lambda n: -1 if n < 0 else (1 if n > 0 else 0) def find_black_region_(im, sx, sy, ex, ey): dx = sign_(ex - sx) dy = sign_(ey - sy) if abs(dx) == abs(dy): raise 'findRegion_ can\'t look both horizontally and vertically at once.' pixel_changes = [] pixel_on = False x = sx y = sy while True: if not pixel_on and im.getpixel((x, y)) == RGBA_BLACK: pixel_changes.append((x, y)) pixel_on = True elif pixel_on and im.getpixel((x, y)) != RGBA_BLACK: pixel_changes.append((x, y)) pixel_on = False x += dx y += dy if x == ex and y == ey: break return (pixel_changes[0][0 if dx else 1] - (sx if dx else sy), pixel_changes[1][0 if dx else 1] - (sx if dx else sy)) def image_to_data_uri_(im): f = StringIO() im.save(f, 'PNG') uri = datauri.to_data_uri(f.getvalue(), 'foo.png') f.close() return uri def main(): src_im = Image.open(sys.argv[1]) # read and parse 9-patch stretch and padding regions stretch_l, stretch_r = find_black_region_(src_im, 0, 0, src_im.size[0], 0) stretch_t, stretch_b = find_black_region_(src_im, 0, 0, 0, src_im.size[1]) pad_l, pad_r = find_black_region_(src_im, 0, src_im.size[1] - 1, src_im.size[0], src_im.size[1] - 1) pad_t, pad_b = find_black_region_(src_im, src_im.size[0] - 1, 0, src_im.size[0] - 1, src_im.size[1]) #padding_box = {} template_params = {} template_params['id'] = sys.argv[1] template_params['icon_uri'] = image_to_data_uri_(src_im) template_params['dim_constraint_attributes'] = '' # p:lockHeight="true" template_params['image_uri'] = image_to_data_uri_(src_im.crop((1, 1, src_im.size[0] - 1, src_im.size[1] - 1))) template_params['width_l'] = stretch_l - 1 template_params['width_r'] = src_im.size[0] - stretch_r - 1 template_params['height_t'] = stretch_t - 1 template_params['height_b'] = src_im.size[1] - stretch_b - 1 template_params['pad_l'] = pad_l - 1 template_params['pad_t'] = pad_t - 1 template_params['pad_r'] = src_im.size[0] - pad_r - 1 template_params['pad_b'] = src_im.size[1] - pad_b - 1 print open('res/shape_9patch_template.xml').read() % template_params if __name__ == '__main__': main()
Python
#!/usr/bin/env python # Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import os import os.path import shutil import zipfile def main(): params = {} params['id'] = sys.argv[1] params['displayname'] = sys.argv[2] params['description'] = sys.argv[3] zip_file = zipfile.ZipFile('dist/stencil-%s.zip' % params['id'], 'w', zipfile.ZIP_DEFLATED) # save stencil XML shapes_xml = '' shapes_folder = 'res/sets/%s/shapes' % params['id'] for shape_file in os.listdir(shapes_folder): if not shape_file.endswith('.xml'): continue shape_xml = open(os.path.join(shapes_folder, shape_file)).read() shapes_xml += shape_xml params['shapes'] = shapes_xml final_xml = open('res/stencil_template.xml').read() % params zip_file.writestr('Definition.xml', final_xml) # save icons icons_folder = 'res/sets/%s/icons' % params['id'] for icon_file in os.listdir(icons_folder): if not icon_file.endswith('.png'): continue zip_file.writestr( 'icons/%s' % icon_file, open(os.path.join(icons_folder, icon_file), 'rb').read()) zip_file.close() if __name__ == '__main__': main()
Python
#!/usr/bin/env python # # hanzim2dict # # Original version written by Michael Robinson (robinson@netrinsics.com) # Version 0.0.2 # Copyright 2004 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # Usage: Run hanzim2dict in a directory containing the "zidianf.gb", # "cidianf.gb", and "sanzidianf.gb" files from the Hanzi Master distribution # (available at http://zakros.ucsd.edu/~arobert/hanzim.html). The output # will be a StarDict dictionary in 2.4.2 format: hanzim.dict, hanzim.idx, # and hanzim.ifo # # The dictionary and index files may be compressed as follows: # $ gzip -9 hanzim.idx # $ dictzip hanzim.dict # from string import split from codecs import getdecoder, getencoder from struct import pack class Word: def __init__(self, code, definition): self.code = code self.definition = [definition] def add(self, definition): self.definition.append(definition) wordmap = {} fromGB = getdecoder("GB2312") toUTF = getencoder("utf_8") file = open("zidianf.gb", "r") lines = map(lambda x: split(x[:-1], '\t'), file.readlines()) for line in lines: code = toUTF(fromGB(line[0])[0])[0] pinyin = line[2] definition = '<'+pinyin+'> '+line[3]+' ['+line[1]+']' if wordmap.has_key(code): wordmap[code].add(definition) else: wordmap[code] = Word(code, definition) for filename in ("cidianf.gb", "sanzicidianf.gb"): file = open(filename, "r") lines = map(lambda x: split(x[:-1], '\t'), file.readlines()) for line in lines: if len(line) < 2: print len(line) continue code = toUTF(fromGB(line[0][:-2])[0])[0] definition = line[1]+' ['+line[0][-1:]+']' if wordmap.has_key(code): wordmap[code].add(definition) else: wordmap[code] = Word(code, definition) dict = open("hanzim.dict", "wb") idx = open("hanzim.idx", "wb") ifo = open("hanzim.ifo", "wb") offset = 0 count = 0 keylen = 0 keys = list(wordmap.keys()) keys.sort() for key in keys: word = wordmap[key] deftext = "" multi = False for d in word.definition: if multi: deftext += '\n' deftext += d multi = True dict.write(deftext) idx.write(key+'\0') idx.write(pack("!I", offset)) idx.write(pack("!I", len(deftext))) offset += len(deftext) count += 1 keylen += len(key) dict.close() idx.close() ifo.write("StarDict's dict ifo file\n") ifo.write("version=2.4.2\n") ifo.write("bookname=Hanzi Master 1.3\n") ifo.write("wordcount="+str(count)+"\n") ifo.write("idxfilesize="+str(keylen+(count*9))+"\n") ifo.write("author=Adrian Robert\n") ifo.write("email=arobert@cogsci.ucsd.edu\n") ifo.write("website=http://zakros.ucsd.edu/~arobert/hanzim.html\n") ifo.write("sametypesequence=m\n") ifo.close()
Python
# This tool convert KangXiZiDian djvu files to tiff files. # Download djvu files: http://bbs.dartmouth.edu/~fangq/KangXi/KangXi.tar # Character page info: http://wenq.org/unihan/Unihan.txt as kIRGKangXi field. # Character seek position in Unihan.txt http://wenq.org/unihan/unihandata.txt # DjVuLibre package provides the ddjvu tool. # The 410 page is bad, but it should be blank page in fact. so just remove 410.tif import os if __name__ == "__main__": os.system("mkdir tif") pages = range(1, 1683+1) for i in pages: page = str(i) print(page) os.system("ddjvu -format=tiff -page="+ page + " -scale=100 -quality=150 KangXiZiDian.djvu"+ " tif/" + page + ".tif")
Python
#!/usr/bin/python # WinVNKey Hannom Database to Stardict dictionary source Conversion Tool # coded by wesnoth@ustc on 070804 # http://winvnkey.sourceforge.net import sys, os, string, types, pprint infileencoding = 'utf-16-le' outfileencoding = 'utf-8' def showhelp(): print "Usage: %s filename" % sys.argv[0] def ishantu(str): if len(str) > 0 and ord(str[0]) > 0x2e80: return True else: return False def mysplit(line): status = 0 # 0: normal, 1: quote i = 0 line = line.lstrip() linelen = len(line) while i < linelen: if status == 0 and line[i].isspace(): break if line[i] == u'"': status = 1 - status i += 1 #print 'mysplit: i=%d, line=%s' % (i, `line`) if i == 0: return [] else: line = [line[:i], line[i:].strip()] if line[1] == u'': return [line[0]] else: return line if __name__ == '__main__': if len(sys.argv) <> 2: showhelp() else: fp = open(sys.argv[1], 'r') print 'Reading file...' lines = unicode(fp.read(), infileencoding).split(u'\n') lineno = 0 hugedict = {} print 'Generating Han-Viet dict...' for line in lines: lineno += 1 if line.endswith(u'\r'): line = line[:-1] if line.startswith(u'\ufeff'): line = line[1:] ind = line.find(u'#') if ind >= 0: line = line[:ind] line = mysplit(line) if len(line) == 0: continue elif len(line) == 1: continue # ignore this incomplete line if line[0].startswith(u'"') and line[0].endswith(u'"'): line[0] = line[0][1:-1] if line[0].startswith(u'U+') or line[0].startswith(u'u+'): line[0] = unichr(int(line[0][2:], 16)) if not ishantu(line[0]): continue # invalid Han character #print 'error occurred on line %d: %s' % (lineno, `line`) if line[1].startswith(u'"') and line[1].endswith(u'"'): line[1] = line[1][1:-1] line[1] = filter(None, map(string.strip, line[1].split(u','))) #hugedict[line[0]] = hugedict.get(line[0], []) + line[1] for item in line[1]: if not hugedict.has_key(line[0]): hugedict[line[0]] = [item] elif not item in hugedict[line[0]]: hugedict[line[0]] += [item] #print lineno, `line` #for hantu, quocngu in hugedict.iteritems(): # print hantu.encode('utf-8'), ':', # for viettu in quocngu: # print viettu.encode('utf-8'), ',', # print fp.close() print 'Generating Viet-Han dict...' dicthuge = {} for hantu, quocngu in hugedict.iteritems(): for viettu in quocngu: if not dicthuge.has_key(viettu): dicthuge[viettu] = [hantu] elif not hantu in dicthuge[viettu]: dicthuge[viettu] += [hantu] print 'Writing Han-Viet dict...' gp = open('hanviet.txt', 'w') for hantu, quocngu in hugedict.iteritems(): gp.write(hantu.encode('utf-8')) gp.write('\t') gp.write((u', '.join(quocngu)).encode('utf-8')) gp.write('\n') gp.close() print 'Writing Viet-Han dict...' gp = open('viethan.txt', 'w') for quocngu,hantu in dicthuge.iteritems(): gp.write(quocngu.encode('utf-8')) gp.write('\t') gp.write((u' '.join(hantu)).encode('utf-8')) gp.write('\n') gp.close()
Python
#!/usr/bin/env python2 # # converts XML JMDict to Stardict idx/dict format # JMDict website: http://www.csse.monash.edu.au/~jwb/j_jmdict.html # # Date: 3rd July 2003 # Author: Alastair Tse <acnt2@cam.ac.uk> # License: BSD (http://www.opensource.org/licenses/bsd-license.php) # # Usage: jm2stardict expects the file JMdict.gz in the current working # directory and outputs to files jmdict-ja-en and jmdict-en-ja # # To compress the resulting files, use: # # gzip -9 jmdict-en-ja.idx # gzip -9 jmdict-ja-en.idx # dictzip jmdict-en-ja.dict # dictzip jmdict-ja-en.dict # # note - dictzip is from www.dict.org # import xml.sax from xml.sax.handler import * import gzip import struct, sys, string, codecs,os def text(nodes): label = "" textnodes = filter(lambda x: x.nodeName == "#text", nodes) for t in textnodes: label += t.data return label def strcasecmp(a, b): result = 0 # to ascii #str_a = string.join(filter(lambda x: ord(x) < 128, a[0]), "").lower() #str_b = string.join(filter(lambda x: ord(x) < 128, b[0]), "").lower() #result = cmp(str_a, str_b) # if result == 0: result = cmp(a[0].lower() , b[0].lower()) return result def merge_dup(list): newlist = [] lastkey = "" for x in list: if x[0] == lastkey: newlist[-1] = (newlist[-1][0], newlist[-1][1] + "\n" + x[1]) else: newlist.append(x) lastkey = x[0] return newlist class JMDictHandler(ContentHandler): def __init__(self): self.mapping = [] self.state = "" self.buffer = "" def startElement(self, name, attrs): if name == "entry": self.kanji = [] self.chars = [] self.gloss = [] self.state = "" self.buffer = "" elif name == "keb": self.state = "keb" elif name == "reb": self.state = "reb" elif name == "gloss" and not attrs: self.state = "gloss" elif name == "xref": self.state = "xref" def endElement(self, name): if name == "entry": self.mapping.append((self.kanji, self.chars, self.gloss)) elif name == "keb": self.kanji.append(self.buffer) elif name == "reb": self.chars.append(self.buffer) elif name == "gloss" and self.buffer: self.gloss.append(self.buffer) elif name == "xref": self.gloss.append(self.buffer) self.buffer = "" self.state = "" def characters(self, ch): if self.state in ["keb", "reb", "gloss", "xref"]: self.buffer = self.buffer + ch def map_to_file(dictmap, filename): dict = open(filename + ".dict","wb") idx = open(filename + ".idx","wb") offset = 0 idx.write("StarDict's idx file\nversion=2.1.0\n"); idx.write("bookname=" + filename + "\nauthor=Jim Breen\nemail=j.breen@csse.monash.edu.au\nwebsite=http://www.csse.monash.edu.au/~jwb/j_jmdict.html\ndescription=Convert to stardict by Alastair Tse <liquidx@gentoo.org>, http://www-lce.eng.cam.ac.uk/~acnt2/code/\ndate=2003.07.01\n") idx.write("sametypesequence=m\n") idx.write("BEGIN:\n") idx.write(struct.pack("!I",len(dictmap))) for k,v in dictmap: k_utf8 = k.encode("utf-8") v_utf8 = v.encode("utf-8") idx.write(k_utf8 + "\0") idx.write(struct.pack("!I",offset)) idx.write(struct.pack("!I",len(v_utf8))) offset += len(v_utf8) dict.write(v_utf8) dict.close() idx.close() if __name__ == "__main__": print "opening xml dict .." f = gzip.open("JMdict.gz") #f = open("jmdict_sample.xml") print "parsing xml file .." parser = xml.sax.make_parser() handler = JMDictHandler() parser.setContentHandler(handler) parser.parse(f) f.close() print "creating dictionary .." # create a japanese -> english mappings jap_to_eng = [] for kanji,chars,gloss in handler.mapping: for k in kanji: key = k value = string.join(chars + gloss, "\n") jap_to_eng.append((key,value)) for c in chars: key = c value = string.join(kanji + gloss, "\n") jap_to_eng.append((key,value)) eng_to_jap = [] for kanji,chars,gloss in handler.mapping: for k in gloss: key = k value = string.join(kanji + chars, "\n") eng_to_jap.append((key,value)) print "sorting dictionary .." jap_to_eng.sort(strcasecmp) eng_to_jap.sort(strcasecmp) print "merging and pruning dups.." jap_to_eng = merge_dup(jap_to_eng) eng_to_jap = merge_dup(eng_to_jap) print "writing to files.." # create dict and idx file map_to_file(jap_to_eng, "jmdict-ja-en") map_to_file(eng_to_jap, "jmdict-en-ja")
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- from gimpfu import * import os def prepare_image(image, visibleLayers, size, numColors = None): """prepare custom image image - image object to change size - size of the image in pixels visibleLayers - a list of layers that must be visible """ for layer in image.layers: if layer.name in visibleLayers: layer.visible = True else: image.remove_layer(layer) gimp.pdb.gimp_image_merge_visible_layers(image, CLIP_TO_IMAGE) drawable=gimp.pdb.gimp_image_get_active_layer(image) gimp.pdb.gimp_layer_scale_full(drawable, size, size, False, INTERPOLATION_CUBIC) """ image 670x670, all layers have the same dimensions after applying gimp_image_scale_full functions with size=32, image.width = 32, image.height = 32 layer.width = 27, layer.height = 31 gimp.pdb.gimp_image_scale_full(image, size, size, INTERPOLATION_CUBIC) """ #print 'width = {0}, height = {1}'.format(drawable.width, drawable.height) #print 'width = {0}, height = {1}'.format(image.width, image.height) if numColors != None: gimp.pdb.gimp_image_convert_indexed(image, NO_DITHER, MAKE_PALETTE, numColors, False, False, "") def save_image(image, dstFilePath): dirPath = os.path.dirname(dstFilePath) if not os.path.exists(dirPath): os.makedirs(dirPath) drawable=gimp.pdb.gimp_image_get_active_layer(image) gimp.pdb.gimp_file_save(image, drawable, dstFilePath, dstFilePath) gimp.delete(drawable) gimp.delete(image) def create_icon(origImage, visibleLayers, props): """visibleLayers - a list of layers that must be visible props - tuple of image properties in format ((size, bpp), ...) where: size - size of the icon in pixels, bpp - bits per pixel, None to leave by default return value - new image """ iconImage = None i = 0 for prop in props: image = gimp.pdb.gimp_image_duplicate(origImage) prepare_image(image, visibleLayers, prop[0], prop[1]) image.layers[0].name = 's{0}'.format(i) if iconImage == None: iconImage = image else: newLayer = gimp.pdb.gimp_layer_new_from_drawable(image.layers[0], iconImage) gimp.pdb.gimp_image_add_layer(iconImage, newLayer, -1) gimp.delete(image) i += 1 return iconImage def stardict_images(srcFilePath, rootDir): if not rootDir: # srcFilePath = rootDir + "/pixmaps/stardict.xcf" if not srcFilePath.endswith("/pixmaps/stardict.xcf"): print 'Unable to automatically detect StarDict root directory. Specify non-blank root directory parameter.' return dstDirPath = os.path.dirname(srcFilePath) dstDirPath = os.path.dirname(dstDirPath) else: dstDirPath = rootDir """ print 'srcFilePath = {0}'.format(srcFilePath) print 'rootDir = {0}'.format(rootDir) print 'dstDirPath = {0}'.format(dstDirPath) """ dstStarDict_s128_FilePath=os.path.join(dstDirPath, "pixmaps/stardict_128.png") dstStarDict_s32_FilePath=os.path.join(dstDirPath, "pixmaps/stardict_32.png") dstStarDict_s16_FilePath=os.path.join(dstDirPath, "pixmaps/stardict_16.png") dstStarDict_FilePath=os.path.join(dstDirPath, "pixmaps/stardict.png") dstStarDictEditor_s128_FilePath=os.path.join(dstDirPath, "pixmaps/stardict-editor_128.png") dstStarDictEditor_s32_FilePath=os.path.join(dstDirPath, "pixmaps/stardict-editor_32.png") dstStarDictEditor_s16_FilePath=os.path.join(dstDirPath, "pixmaps/stardict-editor_16.png") dstStarDictIconFilePath=os.path.join(dstDirPath, "pixmaps/stardict.ico") dstStarDictEditorIconFilePath=os.path.join(dstDirPath, "pixmaps/stardict-editor.ico") dstStarDictUninstIconFilePath=os.path.join(dstDirPath, "pixmaps/stardict-uninst.ico") dstDockletNormalFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_normal.png") dstDockletScanFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_scan.png") dstDockletStopFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_stop.png") dstDockletGPENormalFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_gpe_normal.png") dstDockletGPEScanFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_gpe_scan.png") dstDockletGPEStopFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_gpe_stop.png") dstWordPickFilePath=os.path.join(dstDirPath, "src/win32/acrobat/win32/wordPick.bmp") origImage=gimp.pdb.gimp_file_load(srcFilePath, srcFilePath) image = gimp.pdb.gimp_image_duplicate(origImage) prepare_image(image, ("book1", "book2"), 128) save_image(image, dstStarDict_s128_FilePath) image = gimp.pdb.gimp_image_duplicate(origImage) prepare_image(image, ("book1", "book2"), 32) save_image(image, dstStarDict_s32_FilePath) image = gimp.pdb.gimp_image_duplicate(origImage) prepare_image(image, ("book1", "book2"), 16) save_image(image, dstStarDict_s16_FilePath) image = gimp.pdb.gimp_image_duplicate(origImage) prepare_image(image, ("book1", "book2"), 64) save_image(image, dstStarDict_FilePath) image = gimp.pdb.gimp_image_duplicate(origImage) prepare_image(image, ("book1", "book2", "edit"), 128) save_image(image, dstStarDictEditor_s128_FilePath) image = gimp.pdb.gimp_image_duplicate(origImage) prepare_image(image, ("book1", "book2", "edit"), 32) save_image(image, dstStarDictEditor_s32_FilePath) image = gimp.pdb.gimp_image_duplicate(origImage) prepare_image(image, ("book1", "book2", "edit"), 16) save_image(image, dstStarDictEditor_s16_FilePath) image = create_icon(origImage, ("book1", "book2"), ((16, None), (32, None), (48, None), (16, 256), (32, 256), (48, 256), (256, None)) ) save_image(image, dstStarDictIconFilePath) image = create_icon(origImage, ("book1", "book2", "edit"), ((16, None), (32, None), (48, None), (16, 256), (32, 256), (48, 256), (256, None)) ) save_image(image, dstStarDictEditorIconFilePath) image = create_icon(origImage, ("book1", "book2", "cross"), ((16, None), (32, None), (48, None), (16, 256), (32, 256), (48, 256), (256, None)) ) save_image(image, dstStarDictUninstIconFilePath) image = gimp.pdb.gimp_image_duplicate(origImage) prepare_image(image, ("book1", "book2"), 32) save_image(image, dstDockletNormalFilePath) image = gimp.pdb.gimp_image_duplicate(origImage) prepare_image(image, ("book1", "book2", "search"), 32) save_image(image, dstDockletScanFilePath) image = gimp.pdb.gimp_image_duplicate(origImage) prepare_image(image, ("book1", "book2", "stop"), 32) save_image(image, dstDockletStopFilePath) image = gimp.pdb.gimp_image_duplicate(origImage) prepare_image(image, ("book1", "book2"), 16) save_image(image, dstDockletGPENormalFilePath) image = gimp.pdb.gimp_image_duplicate(origImage) prepare_image(image, ("book1", "book2", "search"), 16) save_image(image, dstDockletGPEScanFilePath) image = gimp.pdb.gimp_image_duplicate(origImage) prepare_image(image, ("book1", "book2", "stop"), 16) save_image(image, dstDockletGPEStopFilePath) # See AVToolButtonNew function in PDF API Reference # Recommended icon size is 18x18, but it looks too small... image = gimp.pdb.gimp_image_duplicate(origImage) prepare_image(image, ("book1", "book2"), 22) gimp.set_background(192, 192, 192) gimp.pdb.gimp_layer_flatten(image.layers[0]) save_image(image, dstWordPickFilePath) register( "stardict_images", "Create images for StarDict", "Create images for StarDict", "StarDict team", "GPL", "Mar 2011", "<Toolbox>/Tools/stardict images", "", [ (PF_FILE, "src_image", "Multilayer image used as source for all other images in StarDict, " + "normally that is pixmaps/stardict.xcf is StarDict source tree.", None), (PF_DIRNAME, "stardict_dir", "Root directory of StarDict source tree. New images will be saved here.", None) ], [], stardict_images) main()
Python
import sys, string base = {} for line in sys.stdin.readlines(): words = string.split(line[:-1], '\t') if len(words) != 2: print "Error!" exit if base.has_key(words[0]): base[words[0]] += [words[1]] else: base[words[0]] = [words[1]] keys = base.keys() keys.sort() for key in keys: print key,'\t', for val in base[key]: print val,',', print
Python
#!/usr/bin/env python # # uyghur2dict # By Abdisalam (anatilim@gmail.com), inspired by Michael Robinson's hanzim2dict converter. # # Original version, hanzim2dict, written by Michael Robinson (robinson@netrinsics.com) # Version 0.0.2 # Copyright 2004 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # Usage: Run hanzim2dict in a directory containing the "zidianf.gb", # "cidianf.gb", and "sanzidianf.gb" files from the Hanzi Master distribution # (available at http://zakros.ucsd.edu/~arobert/hanzim.html). The output # will be a StarDict dictionary in 2.4.2 format: hanzim.dict, hanzim.idx, # and hanzim.ifo # # The dictionary and index files may be compressed as follows: # $ gzip -9 hanzim.idx # $ dictzip hanzim.dict # from string import split from struct import pack class Word: def __init__(self, code, definition): self.code = code self.definition = [definition] def add(self, definition): self.definition.append(definition) wordmap = {} file = open("ChineseUyghurStarDict.txt", "r") lines = map(lambda x: split(x[:-1], '\t\t'), file.readlines()) for line in lines: code = line[0] definition = line[1] if wordmap.has_key(code): wordmap[code].add(definition) else: wordmap[code] = Word(code, definition) dict = open("Anatilim_Chinese_Uyghur.dict", "wb") idx = open("Anatilim_Chinese_Uyghur.idx", "wb") ifo = open("Anatilim_Chinese_Uyghur.ifo", "wb") offset = 0 count = 0 keylen = 0 keys = list(wordmap.keys()) keys.sort() for key in keys: word = wordmap[key] deftext = "" for d in word.definition: deftext=d deftext += '\0' dict.write(deftext) idx.write(key+'\0') idx.write(pack("!I", offset)) idx.write(pack("!I", len(deftext))) offset += len(deftext) count += 1 keylen += len(key) dict.close() idx.close() ifo.write("StarDict's dict ifo file\n") ifo.write("version=2.4.2\n") ifo.write("bookname=Anatilim 《汉维词典》-- Anatilim Chinese Uyghur Dictionary\n") ifo.write("wordcount="+str(count)+"\n") ifo.write("idxfilesize="+str(keylen+(count*9))+"\n") ifo.write("author=Abdisalam\n") ifo.write("email=anatilim@gmail.com\n") ifo.write("description=感谢新疆维吾尔自治区语委会、新疆青少年出版社为我们提供《汉维词典》的词库\n") ifo.write("sametypesequence=m\n") ifo.close()
Python
import sys, string for line in sys.stdin.readlines(): words = string.split(line[:-1], '\t') muci = words[1] sheng = words[2] deng = words[3] hu = words[4] yunbu = words[5] diao = words[6] fanqie= words[7] she = words[8] chars = words[9] romazi= words[10] beizhu= words[12] pinyin= words[13] psyun = words[22] if beizhu == '': print "%s\t%s %s%s%s%s%s%s %sQIE PINYIN%s PSYUN%s\\n%s" % (romazi, muci, sheng, yunbu, she, hu, deng, diao, fanqie, pinyin, psyun, chars) else: print "%s\t%s %s%s%s%s%s%s %sQIE PINYIN%s PSYUN%s\\n%s\\n%s" % (romazi, muci, sheng, yunbu, she, hu, deng, diao, fanqie, pinyin, psyun, chars, beizhu)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- import sys, os, string, re, glob import libxml2dom fencoding = 'utf-8' whattoextract = u'康熙字典' #def TextInNode(node): # result = u'' # for child in node.childNodes: # if child.nodeType == child.TEXT_NODE: # result += child.nodeValue # else: # result += TextInNode(child) # return result filelist = glob.glob('*.htm') filenum = len(filelist) num = 0 errorfiles = [] for filename in filelist: num += 1 print >> sys.stderr, filename, num, 'of', filenum try: fp = open(filename, 'r') doc = libxml2dom.parseString(fp.read(), html=1) fp.close() style = doc.getElementsByTagName("style")[0].textContent style = re.search(r'(?s)\s*\.(\S+)\s*{\s*display:\s*none', style) displaynone = style.group(1) tabpages = doc.getElementsByTagName("div") tabpages = filter(lambda s: s.getAttribute("class") == "tab-page", tabpages) for tabpage in tabpages: found = False for node in tabpage.childNodes: if node.nodeType == node.ELEMENT_NODE and node.name == 'h2': if node.textContent == whattoextract: found = True break if found: spans = tabpage.getElementsByTagName("span") for span in spans: if span.getAttribute("class") == "kszi": character = span.textContent paragraphs = tabpage.getElementsByTagName("p") thisitem = character + u'\t' for paragraph in paragraphs: if paragraph.getAttribute("class") <> displaynone: #print TextInNode(paragraph).encode(fencoding) text = paragraph.textContent #text = filter(lambda s: not s in u' \t\r\n', text) text = re.sub(r'\s+', r' ', text) thisitem += text + u'\\n' print thisitem.encode(fencoding) except: print >> sys.stderr, 'error occured' errorfiles += [filename] continue if errorfiles: print >> sys.stderr, 'Error files:', '\n'.join(errorfiles)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Script for decoding Lingea Dictionary (.trd) file # Result is <header>\t<definition> file, convertable easily # by stardict-editor from package stardict-tools into native # Stardict dictionary (stardict.sf.net and www.stardict.org) # # Copyright (C) 2007 - Klokan Petr Přidal (www.klokan.cz) # # Based on script CobuildConv.rb by Nomad # http://hp.vector.co.jp/authors/VA005784/cobuild/cobuildconv.html # # Version history: # 0.4 (30.10.2007) Patch by Petr Dlouhy, optional HTML generation # 0.3 (28.10.2007) Patch by Petr Dlouhy, cleanup, bugfix. More dictionaries. # 0.2 (19.7.2007) Changes, documentation, first 100% dictionary # 0.1 (20.5.2006) Initial version based on Nomad specs # # Supported dictionaries: # - Lingea Německý Kapesní slovník # - Lingea Anglický Kapesní slovník # - Lingea 2002 series (theoretically) # # Modified by: # - Petr Dlouhy (petr.dlouhy | email.cz) # Generalization of data block rules, sampleFlag 0x04, sound out fix, data phrase prefix with comment (0x04) # HTML output, debugging patch, options on command line # # <write your name here> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for more details. # # You should have received a copy of the GNU Library General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. # VERSION VERSION = "0.4" import getopt, sys def usage(): print "Lingea Dictionary Decoder" print "-------------------------" print "Version: %s" % VERSION print "Copyright (C) 2007 - Klokan Petr Pridal, Petr Dlouhy" print print "Usage: python lingea-trd-decoder.py DICTIONARY.trd > DICTIONARY.tab" print "Result convertion by stardict-tools: /usr/lib/stardict-tools/tabfile" print print " -o <num> --out-style : Output style" print " 0 no tags" print " 1 \\n tags" print " 2 html tags" print " -h --help : Print this message" print " -d --debug : Degub" print " -r --debug-header : Degub - print headers" print " -a --debug-all : Degub - print all records" print " -l --debug-limit : Degub limit" print print "For HTML support in StarDict dictionary .ifo has to contain:" print "sametypesequence=g" print "!!! Change the .ifo file after generation by tabfile !!!" print try: opts, args = getopt.getopt(sys.argv[1:], "hdo:ral:", ["help", "debug", "out-style=", "debug-header", "debug-all", "debug-limit="]) except getopt.GetoptError: usage() print "ERROR: Bad option" sys.exit(2) import locale DEBUG = False OUTSTYLE = 2 DEBUGHEADER = False DEBUGALL = False DEBUGLIMIT = 1 for o, a in opts: if o in ("-d", "-debug"): # DEBUGING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! DEBUG = True if o in ("-o", "--out-style"): # output style OUTSTYLE = locale.atoi(a) if OUTSTYLE > 2: usage() print "ERROR: Output style not specified" if o in ("-r", "--debug-header"): # If DEBUG and DEBUGHEADER, then print just all header records DEBUGHEADER = True if o in ("-a", "--debug-all"): # If DEBUG and DEBUGALL then print debug info for all records DEBUGALL = True if o in ("-h", "--help"): usage() sys.exit(0) if o in ("-l", "--debug-limit"): # Number of wrong records for printing to stop during debugging DEBUGLIMIT = locale.atoi(a) # FILENAME is a first parameter on the commandline now if len(args) == 1: FILENAME = args[0] else: usage() print "ERROR: You have to specify .trd file to decode" sys.exit(2) from struct import * import re alpha = ['\x00', 'a','b','c','d','e','f','g','h','i', 'j','k','l','m','n','o','p','q','r','s', 't','u','v','w','x','y','z','#AL27#','#AL28#','#AL29#', '#AL30#','#AL31#', ' ', '.', '<', '>', ',', ';', '-', '#AL39#', '#GRAVE#', '#ACUTE#', '#CIRC#', '#TILDE#', '#UML#', '#AL45#', '#AL46#', '#CARON#', '#AL48#', '#CEDIL#', '#AL50#', '#AL51#', '#GREEK#', '#AL53#', '#AL54#', '#AL55#', '#AL56#', '#AL57#', '#AL58#', '#SYMBOL#', '#AL60#', '#UPCASE#', '#SPECIAL#', '#UNICODE#'] # 4 bytes after unicode upcase = ['#UP0#','#UP1#','#UP2#','#UP3#','#UP4#','#UP5#','#UP6#','#UP7#','#UP8#','#UP9#', '#UP10#','#UP11#','#UP12#','#UP13#','#UP14#','#UP15#','#UP16#','#UP17#','#UP18#','#UP19#', '#UP20#','#UP21#','#UP22#','#UP23#','#UP24#','#UP25#','#UP26#','#UP27#','#UP28#','#UP29#', '#UP30#','#UP31#','A','B','C','D','E','F','G','H', 'I','J','K','L','M','N','O','P','Q','R', 'S','T','U','V','W','X','Y','Z','#UP58#','#UP59#', '#UP60#','#UP61#','#UP62#','#UP63#'] upcase_pron = ['#pr0#', '#pr1#','#pr2#','#pr3#','#pr4#','#pr5#','#pr6#','#pr7#','#pr8#','#pr9#', '#pr10#', '#pr11#','#pr12#','#pr13#','#pr14#','#pr15#','#pr16#','#pr17#','#pr18#','#pr19#', '#pr20#', '#pr21#','#pr22#','#pr23#','#pr24#','#pr25#','#pr26#','#pr27#','#pr28#','#pr29#', '#pr30#', '#pr31#','ɑ','#pr33#','ʧ','ð','ə','ɜ','#pr38#','æ', 'ɪ', 'ɭ','#pr42#','ŋ','#pr44#','ɳ','ɔ','#pr47#','ɒ','ɽ', 'ʃ', 'θ','ʊ','ʌ','#pr54#','#pr55#','#pr56#','ʒ','#pr58#','#pr59#', '#pr60#', '#pr61#','#pr62#','#pr63#'] symbol = ['#SY0#', '#SY1#','#SY2#','#SY3#','§','#SY5#','#SY6#','#SY7#','#SY8#','#SY9#', '#SY10#', '#SY11#','#SY12#','#SY13#','#SY14#','™','#SY16#','#SY17#','¢','£', '#SY20#', '#SY21#','#SY22#','#SY23#','©','#SY25#','#SY26#','#SY27#','®','°', '#SY30#', '²','³','#SY33#','#SY34#','#SY35#','¹','#SY37#','#SY38#','#SY39#', '½', '#SY41#','#SY42#','×','÷','#SY45#','#SY46#','#SY47#','#SY48#','#SY49#', '#SY50#', '#SY51#','#SY52#','#SY53#','#SY54#','#SY55#','#SY56#','#SY57#','#SY58#','#SY59#', '#SY60#', '#SY61#','#SY62#','#SY63#'] special = ['#SP0#', '!','"','#','$','%','&','\'','(',')', '*', '+','#SP12#','#SP13#','#SP14#','/','0','1','2','3', '4', '5','6','7','8','9',':',';','<','=', '>', '?','@','[','\\',']','^','_','`','{', '|', '}','~','#SP43#','#SP44#','#SP45#','#SP46#','#SP47#','#SP48#','#SP49#', '#SP50#', '#SP51#','#SP52#','#SP53#','#SP54#','#SP55#','#SP56#','#SP57#','#SP58#','#SP59#', '#SP60#', '#SP61#','#SP62#','#SP63#'] wordclass = ('#0#','n:','adj:','pron:','#4#','v:','adv:','prep:','#8#','#9#', 'intr:','phr:','#12#','#13#','#14#','#15#','#16#','#17#','#18#','#19#', '#20#','#21#','#22#','#23#','#24#','#25#','#26#','#27#','#28#','#29#', '#30#','#31#') if OUTSTYLE == 0: tag = { 'db':('' ,''), #Data begining 'rn':('' ,'\t'), #Record name 'va':('' ,' '), #Header variant 'wc':('(' ,')'), #WordClass 'pa':('' ,' '), #Header parts 'fo':('(' ,') '), #Header forms 'on':('(' ,')' ), #Header origin note 'pr':('[' ,']'), #Header pronunciation 'dv':('{' ,'} '), #Header dataVariant 'sa':('`' ,'`' ), #Data sample 'sw':('' ,''), #Data sample wordclass; is no printed by Lingea 'do':('`' ,'`' ), #Data origin note 'df':('' ,' '), #Data definition 'ps':('"' ,'" '), #Data phrase short form 'pg':('"' ,' = '), #Data phrase green 'pc':('`' ,'`'), #Data phrase comment; this comment is not printed by Lingea), but it seems useful 'p1':('"' ,' = '), #Data phrase 1 'p2':('' ,'" ' ), #Data phrase 2 'sp':('"' ,' = ' ),#Data simple phrase 'b1':('"' ,' = '), #Data phrase (block) 1 'b2':('" ' ,''), #Data phrase (block) 2 } if OUTSTYLE == 1: tag = { 'db':('•' ,''), #Data begining 'rn':('' ,'\t'), #Record name 'va':('' ,' '), #Header variant 'wc':('' ,'\\n'), #WordClass 'pa':('' ,':\\n'), #Header parts 'fo':('(' ,') '), #Header forms 'on':('(' ,')\\n' ), #Header origin note 'pr':('[' ,']\\n'), #Header pronunciation 'dv':('{' ,'} '), #Header dataVariant 'sa':(' ' ,'\\n' ), #Data sample 'sw':('' ,''), #Data sample wordclass; is not printed by Lingea 'do':(' ' ,' ' ), #Data origin note 'df':(' ' ,'\\n'), #Data definition 'ps':(' ' ,'\\n'), #Data phrase short form 'pg':(' ' ,' '), #Data phrase green 'pc':(' ' ,' '), #Data phrase comment; this comment is not printed by Lingea), but it seems useful 'p1':(' ' ,' '), #Data phrase 1 'p2':(' ' ,'\\n' ), #Data phrase 2 'sp':('' ,'\\n' ), #Data simple phrase 'b1':('"' ,' = '), #Data phrase (block) 1 'b2':('" ' ,''), #Data phrase (block) 2 } if OUTSTYLE == 2: tag = { 'db':('•' ,''), #Data begining 'rn':('' ,'\t'), #Record name 'va':('' ,' '), #Header variant 'wc':('<span size="larger" color="darkred" weight="bold">','</span>\\n'), #WordClass 'pa':('<span size="larger" color="darkred" weight="bold">',':</span>\\n'), #Header parts 'fo':('(' ,') '), #Header forms 'on':('<span color="blue">(' ,')</span>\\n' ), #Header origin note 'pr':('[' ,']\\n'), #Header pronunciation 'dv':('{' ,'} '), #Header dataVariant 'sa':(' <span color="darkred" weight="bold">' ,'</span>\\n' ), #Data sample 'sw':('' ,''), #Data sample wordclass; is not printed by Lingea 'do':(' <span color="darkred" weight="bold">' ,'</span> ' ), #Data origin note 'df':(' <span weight="bold">' ,'</span>\\n'), #Data definition 'ps':(' <span color="dimgray" weight="bold">' ,'</span>\\n'), #Data phrase short form 'pg':(' <span color="darkgreen" style="italic">' ,'</span> '), #Data phrase green 'pc':(' <span color="darkgreen" style="italic">' ,'</span> '), #Data phrase comment; this comment is not printed by Lingea), but it seems useful 'p1':(' <span color="dimgray" style="italic">' ,'</span> '), #Data phrase 1 'p2':(' ' ,'\\n' ), #Data phrase 2 'sp':('<span color="cyan">' ,'</span>\\n' ), #Data simple phrase 'b1':('"' ,' = '), #Data phrase (block) 1 'b2':('" ' ,''), #Data phrase (block) 2 } # Print color debug functions purple = lambda c: '\x1b[1;35m'+c+'\x1b[0m' blue = lambda c: '\x1b[1;34m'+c+'\x1b[0m' cyan = lambda c: '\x1b[36m'+c+'\x1b[0m' gray = lambda c: '\x1b[1m'+c+'\x1b[0m' def getRec(n): """Get data stream for record of given number""" if n >= 0 and n < entryCount: f.seek(index[n]) return f.read(index[n+1] - index[n]) else: return '' def decode_alpha( stream, nullstop=True): """Decode 6-bit encoding data stream from the begining untit first NULL""" offset = 0 triple = 0 result = [] while triple < len( stream ): if offset % 4 == 0: c = stream[triple] >> 2 triple += 1 if offset % 4 == 1: c = (stream[triple-1] & 3) << 4 | stream[triple] >> 4 triple += 1 if offset % 4 == 2: c = (stream[triple-1] & 15) << 2 | (stream[triple] & 192) >> 6 triple += 1 if offset % 4 == 3: c = stream[triple-1] & 63 if c == 0 and nullstop: break offset += 1 # TODO: ENCODE UNICODE 4 BYTE STREAM!!! and but it after #UNICODE# as unichr() result.append(c) return decode_alpha_postprocessing(result), triple - 1 def decode_alpha_postprocessing( input ): """Lowlevel alphabet decoding postprocessing, combines tuples into one character""" result = "" input.extend([0x00]*5) # UPCASE, UPCASE_PRON, SYMBOL, SPECIAL skip = False for i in range(0,len(input)-1): if skip: skip = False continue bc = input[i] c = alpha[bc] bc1 = input[i+1] c1 = alpha[bc1] if bc < 40: result += c else: if c == "#GRAVE#": if c1 == 'a': result += 'à' else: result += '#GRAVE%s#' % c1 elif c == "#UML#": if c1 == 'o': result += 'ö' elif c1 == 'u': result += 'ü' elif c1 == 'a': result += 'ä' elif c1 == ' ': result += 'Ä' elif c1 == '#AL46#': result += 'Ö' elif c1 == '#GREEK#': result += 'Ü' else: result += '#UML%s#' % c1 elif c == "#ACUTE#": if c1 == 'a': result += 'á' elif c1 == 'e': result += 'é' elif c1 == 'i': result += 'í' elif c1 == 'o': result += 'ó' elif c1 == 'u': result += 'ú' elif c1 == 'y': result += 'ý' elif c1 == ' ': result += 'Á' elif c1 == '#GRAVE#': result += 'Í' else: result += '#ACUTE%s#' % c1 elif c == "#CARON#": if c1 == 'r': result += 'ř' elif c1 == 'c': result += 'č' elif c1 == 's': result += 'š' elif c1 == 'z': result += 'ž' elif c1 == 'e': result += 'ě' elif c1 == 'd': result += 'ď' elif c1 == 't': result += 'ť' elif c1 == 'a': result += 'å' elif c1 == 'u': result += 'ů' elif c1 == 'n': result += 'ň' elif c1 == '<': result += 'Č' elif c1 == '#CEDIL#': result += 'Ř' elif c1 == '#AL50#': result += 'Š' elif c1 == '#AL57#': result += 'Ž' else: result += '#CARON%s#' % c1 elif c == "#UPCASE#": result += upcase[bc1] elif c == "#SYMBOL#": result += symbol[bc1] elif c == "#AL51#": if c1 == 's': result += 'ß' elif c == "#AL48#": result += "#AL48#%s" % c1 elif c == "#SPECIAL#": result += special[bc1] elif c == "#UNICODE#": result += '#UNICODE%s#' % bc1 elif c == "#CIRC#": if c1 == 'a': result += 'â' else: result += '#CARON%s#' % c1 else: result += '%sX%s#' % (c[:-1], bc1) skip = True return result def pronunciation_encode(s): """Encode pronunciation upcase symbols into IPA symbols""" for i in range(0, 64): s = s.replace(upcase[i], upcase_pron[i]) return s re_d = re.compile(r'<d(.*?)>') re_w = re.compile(r'<w(.*?)>') re_y = re.compile(r'<y(.*?)>') re_c = re.compile(r'<c(.*?)>') def decode_tag_postprocessing(input): """Decode and replace tags used in lingea dictionaries; decode internal tags""" s = input # General information in http://www.david-zbiral.cz/El-slovniky-plnaverze.htm#_Toc151656799 # TODO: Better output handling if OUTSTYLE == 0: # ?? <d...> s = re_d.sub(r'(\1)',s) # ?? <w...> s = re_w.sub(r'(\1)',s) # ?? <y...> s = re_y.sub(r'(\1)',s) # ?? <c...> s = re_c.sub(r'(\1)',s) # ... if OUTSTYLE == 1: # ?? <d...> s = re_d.sub(r'(\1)',s) # ?? <w...> s = re_w.sub(r'(\1)',s) # ?? <y...> s = re_y.sub(r'(\1)',s) # ?? <c...> s = re_c.sub(r'(\1)',s) # ... if OUTSTYLE == 2: # ?? <d...> s = re_d.sub(r'<span size="small" color="blue">(\1)</span>',s) # ?? <w...> s = re_w.sub(r'<span size="small" color="blue" style="italic">\1</span>',s) # ?? <y...> s = re_y.sub(r'<span size="small" color="blue" style="italic">\1</span>',s) # ?? <c...> s = re_c.sub(r'<span size="small" color="blue" style="italic">\1</span>',s) # ... return s def toBin( b ): """Prettify debug output format: hex(bin)dec""" original = b r = 0; i = 1; while b > 0: if b & 0x01 != 0: r += i i *= 10 b = b >> 1 return "0x%02X(%08d)%03d" % (original, r, original) def out( comment = "", skip = False): """Read next byte or string (with skip=True) and output DEBUG info""" global bs, pos s, triple = decode_alpha(bs[pos:]) s = s.split('\x00')[0] # give me string until first NULL if (comment.find('%') != -1): if skip: comment = comment % s else: comment = comment % bs[pos] if DEBUG: print "%03d %s %s | %s | %03d" % (pos, toBin(bs[pos]),comment, s, (triple + pos)) if skip: pos += triple + 1 return s.replace('`','') # Remove '`' character from words else: pos += 1 return bs[pos-1] outInt = lambda c: out(c) outStr = lambda c: out(c, True) def decode(stream): """Decode byte stream of one record, return decoded string with formatting in utf""" result = "" global bs, pos # stream - data byte stream for one record bs = unpack("<%sB" % len(stream), stream) # bs - list of bytes from stream pos = 0 itemCount = outInt("ItemCount: %s") # Number of blocks in the record mainFlag = outInt("MainFlag: %s") # HEADER BLOCK # ------------ if mainFlag & 0x01: headerFlag = outInt("HeaderFlag: %s") # Blocks in header if headerFlag & 0x01: result += tag['rn'][0] + outStr("Header record name: %s").replace('_','') + tag['rn'][1] # Remove character '_' from index if headerFlag & 0x02: result += tag['va'][0] + outStr("Header variant: %s") + tag['va'][1] if headerFlag & 0x04: s = outInt("Header wordclass: %s") if s < 32: result += tag['wc'][0] + wordclass[s] + tag['wc'][1] else: raise "Header wordclass out of range in: %s" % result if headerFlag & 0x08: result += tag['pa'][0] + outStr("Header parts: %s") + tag['pa'][1] if headerFlag & 0x10: result += tag['fo'][0] + outStr("Header forms: %s") + tag['fo'][1] if headerFlag & 0x20: result += tag['on'][0] + outStr("Header origin note: %s") + tag['on'][1] if headerFlag & 0x80: result += tag['pr'][0] + pronunciation_encode(outStr("Header pronunciation: %s")) + tag['pr'][1] # Header data block if mainFlag & 0x02: headerFlag = outInt("Header dataFlag: %s") # Blocks in header if headerFlag & 0x02: result += tag['dv'][0] + outStr("Header dataVariant: %s")+ tag['dv'][1] # ??? Link elsewhere pass # SOUND DATA REFERENCE if mainFlag & 0x80: outInt("Sound reference byte #1: %s") outInt("Sound reference byte #2: %s") outInt("Sound reference byte #3: %s") outInt("Sound reference byte #4: %s") outInt("Sound reference byte #5: %s") #out("Sound data reference (5 bytes)", 6) # TODO: Test all mainFlags in header!!!! #result += ': ' li = 0 #print just every first word class identifier # TODO: this is not systematic (should be handled by output) global lastWordClass lastWordClass = 0 # DATA BLOCK(S) # ------------- for i in range(0, itemCount): item = tag['db'][0] + tag['db'][1] ol = False dataFlag = outInt("DataFlag: %s -----------------------------") if dataFlag & 0x01: # small index sampleFlag = outInt("Data sampleFlag: %s") if sampleFlag & 0x01: result += tag['sa'][0] + outStr("Data sample: %s") + tag['sa'][1] if sampleFlag & 0x04: s = outInt("Data wordclass: %s") if s != lastWordClass: if s < 32: result += tag['wc'][0] + wordclass[s] + tag['wc'][1] else: raise "Header wordclass out of range in: %s" % result lastWordClass = s if sampleFlag & 0x08: result += tag['sw'][0] + outStr("Data sample wordclass: %s") + tag['sw'][1] if sampleFlag & 0x10: outInt("Data sample Int: %s") outInt("Data sample Int: %s") outInt("Data sample Int: %s") if sampleFlag & 0x20: item += tag['do'][0] + outStr("Data origin note: %s") + tag['do'][1] if sampleFlag & 0x80: item += " " result += tag['pr'][0] + pronunciation_encode(outStr("Data sample pronunciation: %s")) + tag['pr'][1] if dataFlag & 0x02: item += " " subFlag = outInt("Data subFlag: %s") if subFlag == 0x80: outStr("Data sub prefix: %s") # It seams that data sub prefix content is ignored and there is a generated number for the whole block instead. li += 1 ol = True if dataFlag & 0x04: # chart pass # ??? if dataFlag & 0x08: # reference item += tag['df'][0] + outStr("Data definition: %s") + tag['df'][1] if dataFlag & 0x10: pass # ??? if dataFlag & 0x20: # phrase phraseFlag1 = outInt("Data phraseFlag1: %s") if phraseFlag1 & 0x01: item += tag['ps'][0] + outStr("Data phrase short form: %s") + tag['ps'][1] if phraseFlag1 & 0x02: phraseCount = outInt("Data phraseCount: %s") for i in range(0, phraseCount): phraseComment = outInt("Data phrase prefix") if phraseComment & 0x04: item += tag['pc'][0] + outStr("Data phrase comment: %s") + tag['pc'][1] item += tag['p1'][0] + outStr("Data phrase 1: %s") + tag['p1'][1] item += tag['p2'][0] + outStr("Data phrase 2: %s") + tag['p2'][1] if phraseFlag1 & 0x04: phraseCount = outInt("Data phraseCount: %s") for i in range(0, phraseCount): phraseComment = outInt("Data phrase prefix") if phraseComment & 0x04: item += tag['pc'][0] + outStr("Data phrase 1: %s") + tag['pc'][1] item += tag['pg'][0] + outStr("Data phrase comment: %s") + tag['pg'][1] item += tag['p2'][0] + outStr("Data phrase 2: %s") + tag['p2'][1] if phraseFlag1 & 0x08: phraseCount = outInt("Data simple phraseCount: %s") for i in range(0, phraseCount): item += " " item += tag['sp'][0] + outStr("Data simple phrase: %s") + tag['sp'][1] if phraseFlag1 & 0x40: item += tag['ps'][0] + outStr("Data phrase short form: %s") + tag['ps'][1] # TODO: be careful in changing the rules, to have back compatibility! if dataFlag & 0x40: # reference, related language #0x01 synonym ? #0x02 antonym ? pass if dataFlag & 0x80: # Phrase block flags = [ out("Data phrase block: %s"), out("Data phrase block: %s"), out("Data phrase block: %s"), out("Data phrase block: %s"), out("Data phrase block: %s"), out("Data phrase block: %s"), out("Data phrase block: %s"), out("Data phrase block: %s")] if flags == [0x80,0x80,0xF9,0xDF,0x9D,0x00,0x0B,0x01]: result += "\\nphr: " li = 1 ol = True item += tag['b1'][0]+outStr("Data phrase 1: %s") + tag['b1'][1] out("Data phrase block: %s") out("Data phrase block: %s") out("Data phrase block: %s") out("Data phrase block: %s") item += tag['ds'][0] + outStr("Data phrase 2: %s") + tag['ds'][1] if flags == [0x80,0x80,0xF9,0xDF,0x9D,0x00,0x23,0x01]: result += "\\nphr: " li = 1 ol = True item += tag['b1'][0]+outStr("Data phrase 1: %s") + tag['b1'][1] out("Data phrase block: %s") out("Data phrase block: %s") out("Data phrase block: %s") out("Data phrase block: %s") out("Data phrase block: %s") item += tag['ds'][0] + outStr("Data phrase 2: %s") + tag['ds'][1] if ol: result += "\\n%d. %s" % (li, item) else: result += item ok = True while pos < len(stream): ok = (out() == 0x00) and ok if ok: result += '\n' return decode_tag_postprocessing(result) ################################################################ # MAIN ################################################################ f = open(FILENAME,'rb') # DECODE HEADER OF FILE copyright = unpack("<64s",f.read(64))[0] a = unpack("<16L",f.read(64)) entryCount = a[4] indexBaseCount = a[6] indexOffsetCount = a[7] pos1 = a[8] indexPos = a[9] bodyPos = a[10] smallIndex = (a[3] == 2052) # DECODE INDEX STRUCTURE OF FILE index = [] f.seek(indexPos) bases = unpack("<%sL" % indexBaseCount, f.read(indexBaseCount * 4)) if smallIndex: # In small dictionaries every base is used 4-times bases4 = [] for i in bases: bases4.extend([i,i,i,i]) bases = bases4 for b in bases: offsets = unpack("<64H", f.read(64*2)) for o in offsets: if len(index) < indexOffsetCount: #print "Index %s: %s + %s + %s * 4 = %s" % (len(index), bodyPos, b, o, toBin(bodyPos + b + o * 4)) index.append(bodyPos + b + o * 4) # DECODE RECORDS if DEBUG: # PRINTOUT DEBUG OF FIRST <DEBUGLIMIT> WRONG RECORDS: for i in range(1,entryCount): if not DEBUGALL: DEBUG = False s = decode(getRec(i)) if DEBUGHEADER: # print s.split('\t')[0] print s if DEBUGLIMIT > 0 and not s.endswith('\n'): DEBUG = True print "-"*80 print "%s) at address %s" % (i, toBin(index[i])) print s = decode(getRec(i)) print s DEBUGLIMIT -= 1 DEBUG = True else: # DECODE EACH RECORD AND PRINT IT IN FORMAT FOR stardict-editor <term>\t<definition> for i in range(1,entryCount): s = decode(getRec(i)) if s.endswith('\n'): print s, else: print s print "!!! RECORD STRUCTURE DECODING ERROR !!!" print "Please run this script in DEBUG mode and repair DATA BLOCK(S) section in function decode()" print "If you succeed with whole dictionary send report (name of the dictionary and source code of script) to slovniky@googlegroups.com" break
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Load application resources from a known path. Loading resources by specifying relative paths to filenames is often problematic in Python, as the working directory is not necessarily the same directory as the application's script files. This module allows applications to specify a search path for resources. Relative paths are taken to be relative to the application's __main__ module. ZIP files can appear on the path; they will be searched inside. The resource module also behaves as expected when applications are bundled using py2exe or py2app. As well as providing file references (with the `file` function), the resource module also contains convenience functions for loading images, textures, fonts, media and documents. 3rd party modules or packages not bound to a specific application should construct their own `Loader` instance and override the path to use the resources in the module's directory. Path format ^^^^^^^^^^^ The resource path `path` (see also `Loader.__init__` and `Loader.path`) is a list of locations to search for resources. Locations are searched in the order given in the path. If a location is not valid (for example, if the directory does not exist), it is skipped. Locations in the path beginning with an ampersand (''@'' symbol) specify Python packages. Other locations specify a ZIP archive or directory on the filesystem. Locations that are not absolute are assumed to be relative to the script home. Some examples:: # Search just the `res` directory, assumed to be located alongside the # main script file. path = ['res'] # Search the directory containing the module `levels.level1`, followed # by the `res/images` directory. path = ['@levels.level1', 'res/images'] Paths are always case-sensitive and forward slashes are always used as path separators, even in cases when the filesystem or platform does not do this. This avoids a common programmer error when porting applications between platforms. The default path is ``['.']``. If you modify the path, you must call `reindex`. :since: pyglet 1.1 ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import os import weakref import sys import zipfile import pyglet from pyglet.compat import BytesIO class ResourceNotFoundException(Exception): '''The named resource was not found on the search path.''' def __init__(self, name): message = ('Resource "%s" was not found on the path. ' 'Ensure that the filename has the correct captialisation.') % name Exception.__init__(self, message) def get_script_home(): '''Get the directory containing the program entry module. For ordinary Python scripts, this is the directory containing the ``__main__`` module. For executables created with py2exe the result is the directory containing the running executable file. For OS X bundles created using Py2App the result is the Resources directory within the running bundle. If none of the above cases apply and the file for ``__main__`` cannot be determined the working directory is returned. When the script is being run by a Python profiler, this function may return the directory where the profiler is running instead of the directory of the real script. To workaround this behaviour the full path to the real script can be specified in `pyglet.resource.path`. :rtype: str ''' frozen = getattr(sys, 'frozen', None) if frozen in ('windows_exe', 'console_exe'): return os.path.dirname(sys.executable) elif frozen == 'macosx_app': # py2app return os.environ['RESOURCEPATH'] else: main = sys.modules['__main__'] if hasattr(main, '__file__'): return os.path.dirname(os.path.abspath(main.__file__)) else: # cx_Freeze return os.path.dirname(sys.executable) # Probably interactive return '' def get_settings_path(name): '''Get a directory to save user preferences. Different platforms have different conventions for where to save user preferences, saved games, and settings. This function implements those conventions. Note that the returned path may not exist: applications should use ``os.makedirs`` to construct it if desired. On Linux, a directory `name` in the user's configuration directory is returned (usually under ``~/.config``). On Windows (including under Cygwin) the `name` directory in the user's ``Application Settings`` directory is returned. On Mac OS X the `name` directory under ``~/Library/Application Support`` is returned. :Parameters: `name` : str The name of the application. :rtype: str ''' if pyglet.compat_platform in ('cygwin', 'win32'): if 'APPDATA' in os.environ: return os.path.join(os.environ['APPDATA'], name) else: return os.path.expanduser('~/%s' % name) elif pyglet.compat_platform == 'darwin': return os.path.expanduser('~/Library/Application Support/%s' % name) elif pyglet.compat_platform.startswith('linux'): if 'XDG_CONFIG_HOME' in os.environ: return os.path.join(os.environ['XDG_CONFIG_HOME'], name) else: return os.path.expanduser('~/.config/%s' % name) else: return os.path.expanduser('~/.%s' % name) class Location(object): '''Abstract resource location. Given a location, a file can be loaded from that location with the `open` method. This provides a convenient way to specify a path to load files from, and not necessarily have that path reside on the filesystem. ''' def open(self, filename, mode='rb'): '''Open a file at this location. :Parameters: `filename` : str The filename to open. Absolute paths are not supported. Relative paths are not supported by most locations (you should specify only a filename with no path component). `mode` : str The file mode to open with. Only files opened on the filesystem make use of this parameter; others ignore it. :rtype: file object ''' raise NotImplementedError('abstract') class FileLocation(Location): '''Location on the filesystem. ''' def __init__(self, path): '''Create a location given a relative or absolute path. :Parameters: `path` : str Path on the filesystem. ''' self.path = path def open(self, filename, mode='rb'): return open(os.path.join(self.path, filename), mode) class ZIPLocation(Location): '''Location within a ZIP file. ''' def __init__(self, zip, dir): '''Create a location given an open ZIP file and a path within that file. :Parameters: `zip` : ``zipfile.ZipFile`` An open ZIP file from the ``zipfile`` module. `dir` : str A path within that ZIP file. Can be empty to specify files at the top level of the ZIP file. ''' self.zip = zip self.dir = dir def open(self, filename, mode='rb'): if self.dir: path = self.dir + '/' + filename else: path = filename text = self.zip.read(path) return BytesIO(text) class URLLocation(Location): '''Location on the network. This class uses the ``urlparse`` and ``urllib2`` modules to open files on the network given a URL. ''' def __init__(self, base_url): '''Create a location given a base URL. :Parameters: `base_url` : str URL string to prepend to filenames. ''' self.base = base_url def open(self, filename, mode='rb'): import urlparse import urllib2 url = urlparse.urljoin(self.base, filename) return urllib2.urlopen(url) class Loader(object): '''Load program resource files from disk. The loader contains a search path which can include filesystem directories, ZIP archives and Python packages. :Ivariables: `path` : list of str List of search locations. After modifying the path you must call the `reindex` method. `script_home` : str Base resource location, defaulting to the location of the application script. ''' def __init__(self, path=None, script_home=None): '''Create a loader for the given path. If no path is specified it defaults to ``['.']``; that is, just the program directory. See the module documentation for details on the path format. :Parameters: `path` : list of str List of locations to search for resources. `script_home` : str Base location of relative files. Defaults to the result of `get_script_home`. ''' if path is None: path = ['.'] if type(path) in (str, unicode): path = [path] self.path = list(path) if script_home is None: script_home = get_script_home() self._script_home = script_home self._index = None # Map bin size to list of atlases self._texture_atlas_bins = {} def _require_index(self): if self._index is None: self.reindex() def reindex(self): '''Refresh the file index. You must call this method if `path` is changed or the filesystem layout changes. ''' # map name to image etc. self._cached_textures = weakref.WeakValueDictionary() self._cached_images = weakref.WeakValueDictionary() self._cached_animations = weakref.WeakValueDictionary() self._index = {} for path in self.path: if path.startswith('@'): # Module name = path[1:] try: module = __import__(name) except: continue for component in name.split('.')[1:]: module = getattr(module, component) if hasattr(module, '__file__'): path = os.path.dirname(module.__file__) else: path = '' # interactive elif not os.path.isabs(path): # Add script base unless absolute assert '\\' not in path, \ 'Backslashes not permitted in relative path' path = os.path.join(self._script_home, path) if os.path.isdir(path): # Filesystem directory path = path.rstrip(os.path.sep) location = FileLocation(path) for dirpath, dirnames, filenames in os.walk(path): dirpath = dirpath[len(path) + 1:] # Force forward slashes for index if dirpath: parts = filter(None, dirpath.split(os.sep)) dirpath = '/'.join(parts) for filename in filenames: if dirpath: index_name = dirpath + '/' + filename else: index_name = filename self._index_file(index_name, location) else: # Find path component that is the ZIP file. dir = '' old_path = None while path and not os.path.isfile(path): old_path = path path, tail_dir = os.path.split(path) if path == old_path: break dir = '/'.join((tail_dir, dir)) if path == old_path: continue dir = dir.rstrip('/') # path is a ZIP file, dir resides within ZIP if path and zipfile.is_zipfile(path): zip = zipfile.ZipFile(path, 'r') location = ZIPLocation(zip, dir) for zip_name in zip.namelist(): #zip_name_dir, zip_name = os.path.split(zip_name) #assert '\\' not in name_dir #assert not name_dir.endswith('/') if zip_name.startswith(dir): if dir: zip_name = zip_name[len(dir)+1:] self._index_file(zip_name, location) def _index_file(self, name, location): if name not in self._index: self._index[name] = location def file(self, name, mode='rb'): '''Load a resource. :Parameters: `name` : str Filename of the resource to load. `mode` : str Combination of ``r``, ``w``, ``a``, ``b`` and ``t`` characters with the meaning as for the builtin ``open`` function. :rtype: file object ''' self._require_index() try: location = self._index[name] return location.open(name, mode) except KeyError: raise ResourceNotFoundException(name) def location(self, name): '''Get the location of a resource. This method is useful for opening files referenced from a resource. For example, an HTML file loaded as a resource might reference some images. These images should be located relative to the HTML file, not looked up individually in the loader's path. :Parameters: `name` : str Filename of the resource to locate. :rtype: `Location` ''' self._require_index() try: return self._index[name] except KeyError: raise ResourceNotFoundException(name) def add_font(self, name): '''Add a font resource to the application. Fonts not installed on the system must be added to pyglet before they can be used with `font.load`. Although the font is added with its filename using this function, it is loaded by specifying its family name. For example:: resource.add_font('action_man.ttf') action_man = font.load('Action Man') :Parameters: `name` : str Filename of the font resource to add. ''' self._require_index() from pyglet import font file = self.file(name) font.add_file(file) def _alloc_image(self, name, atlas=True): file = self.file(name) try: img = pyglet.image.load(name, file=file) finally: file.close() if not atlas: return img.get_texture(True) # find an atlas suitable for the image bin = self._get_texture_atlas_bin(img.width, img.height) if bin is None: return img.get_texture(True) return bin.add(img) def _get_texture_atlas_bin(self, width, height): '''A heuristic for determining the atlas bin to use for a given image size. Returns None if the image should not be placed in an atlas (too big), otherwise the bin (a list of TextureAtlas). ''' # Large images are not placed in an atlas if width > 128 or height > 128: return None # Group images with small height separately to larger height (as the # allocator can't stack within a single row). bin_size = 1 if height > 32: bin_size = 2 try: bin = self._texture_atlas_bins[bin_size] except KeyError: bin = self._texture_atlas_bins[bin_size] = \ pyglet.image.atlas.TextureBin() return bin def image(self, name, flip_x=False, flip_y=False, rotate=0, atlas=True): '''Load an image with optional transformation. This is similar to `texture`, except the resulting image will be packed into a `TextureBin` if it is an appropriate size for packing. This is more efficient than loading images into separate textures. :Parameters: `name` : str Filename of the image source to load. `flip_x` : bool If True, the returned image will be flipped horizontally. `flip_y` : bool If True, the returned image will be flipped vertically. `rotate` : int The returned image will be rotated clockwise by the given number of degrees (a multiple of 90). `atlas` : bool If True, the image will be loaded into an atlas managed by pyglet. If atlas loading is not appropriate for specific texturing reasons (e.g. border control is required) then set this argument to False. :rtype: `Texture` :return: A complete texture if the image is large or not in an atlas, otherwise a `TextureRegion` of a texture atlas. ''' self._require_index() if name in self._cached_images: identity = self._cached_images[name] else: identity = self._cached_images[name] = self._alloc_image(name, atlas=atlas) if not rotate and not flip_x and not flip_y: return identity return identity.get_transform(flip_x, flip_y, rotate) def animation(self, name, flip_x=False, flip_y=False, rotate=0): '''Load an animation with optional transformation. Animations loaded from the same source but with different transformations will use the same textures. :Parameters: `name` : str Filename of the animation source to load. `flip_x` : bool If True, the returned image will be flipped horizontally. `flip_y` : bool If True, the returned image will be flipped vertically. `rotate` : int The returned image will be rotated clockwise by the given number of degrees (a multiple of 90). :rtype: `Animation` ''' self._require_index() try: identity = self._cached_animations[name] except KeyError: animation = pyglet.image.load_animation(name, self.file(name)) bin = self._get_texture_atlas_bin(animation.get_max_width(), animation.get_max_height()) if bin: animation.add_to_texture_bin(bin) identity = self._cached_animations[name] = animation if not rotate and not flip_x and not flip_y: return identity return identity.get_transform(flip_x, flip_y, rotate) def get_cached_image_names(self): '''Get a list of image filenames that have been cached. This is useful for debugging and profiling only. :rtype: list :return: List of str ''' self._require_index() return self._cached_images.keys() def get_cached_animation_names(self): '''Get a list of animation filenames that have been cached. This is useful for debugging and profiling only. :rtype: list :return: List of str ''' self._require_index() return self._cached_animations.keys() def get_texture_bins(self): '''Get a list of texture bins in use. This is useful for debugging and profiling only. :rtype: list :return: List of `TextureBin` ''' self._require_index() return self._texture_atlas_bins.values() def media(self, name, streaming=True): '''Load a sound or video resource. The meaning of `streaming` is as for `media.load`. Compressed sources cannot be streamed (that is, video and compressed audio cannot be streamed from a ZIP archive). :Parameters: `name` : str Filename of the media source to load. `streaming` : bool True if the source should be streamed from disk, False if it should be entirely decoded into memory immediately. :rtype: `media.Source` ''' self._require_index() from pyglet import media try: location = self._index[name] if isinstance(location, FileLocation): # Don't open the file if it's streamed from disk -- AVbin # needs to do it. path = os.path.join(location.path, name) return media.load(path, streaming=streaming) else: file = location.open(name) return media.load(name, file=file, streaming=streaming) except KeyError: raise ResourceNotFoundException(name) def texture(self, name): '''Load a texture. The named image will be loaded as a single OpenGL texture. If the dimensions of the image are not powers of 2 a `TextureRegion` will be returned. :Parameters: `name` : str Filename of the image resource to load. :rtype: `Texture` ''' self._require_index() if name in self._cached_textures: return self._cached_textures[name] file = self.file(name) texture = pyglet.image.load(name, file=file).get_texture() self._cached_textures[name] = texture return texture def html(self, name): '''Load an HTML document. :Parameters: `name` : str Filename of the HTML resource to load. :rtype: `FormattedDocument` ''' self._require_index() file = self.file(name) return pyglet.text.decode_html(file.read(), self.location(name)) def attributed(self, name): '''Load an attributed text document. See `pyglet.text.formats.attributed` for details on this format. :Parameters: `name` : str Filename of the attribute text resource to load. :rtype: `FormattedDocument` ''' self._require_index() file = self.file(name) return pyglet.text.load(name, file, 'text/vnd.pyglet-attributed') def text(self, name): '''Load a plain text document. :Parameters: `name` : str Filename of the plain text resource to load. :rtype: `UnformattedDocument` ''' self._require_index() file = self.file(name) return pyglet.text.load(name, file, 'text/plain') def get_cached_texture_names(self): '''Get the names of textures currently cached. :rtype: list of str ''' self._require_index() return self._cached_textures.keys() #: Default resource search path. #: #: Locations in the search path are searched in order and are always #: case-sensitive. After changing the path you must call `reindex`. #: #: See the module documentation for details on the path format. #: #: :type: list of str path = [] class _DefaultLoader(Loader): def _get_path(self): return path def _set_path(self, value): global path path = value path = property(_get_path, _set_path) _default_loader = _DefaultLoader() reindex = _default_loader.reindex file = _default_loader.file location = _default_loader.location add_font = _default_loader.add_font image = _default_loader.image animation = _default_loader.animation get_cached_image_names = _default_loader.get_cached_image_names get_cached_animation_names = _default_loader.get_cached_animation_names get_texture_bins = _default_loader.get_texture_bins media = _default_loader.media texture = _default_loader.texture html = _default_loader.html attributed = _default_loader.attributed text = _default_loader.text get_cached_texture_names = _default_loader.get_cached_texture_names
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Functions for loading dynamic libraries. These extend and correct ctypes functions. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import os import re import sys import ctypes import ctypes.util import pyglet _debug_lib = pyglet.options['debug_lib'] _debug_trace = pyglet.options['debug_trace'] if pyglet.options['search_local_libs']: script_path = pyglet.resource.get_script_home() _local_lib_paths = [script_path, os.path.join(script_path, 'lib'),] else: _local_lib_paths = None class _TraceFunction(object): def __init__(self, func): self.__dict__['_func'] = func def __str__(self): return self._func.__name__ def __call__(self, *args, **kwargs): return self._func(*args, **kwargs) def __getattr__(self, name): return getattr(self._func, name) def __setattr__(self, name, value): setattr(self._func, name, value) class _TraceLibrary(object): def __init__(self, library): self._library = library print library def __getattr__(self, name): func = getattr(self._library, name) f = _TraceFunction(func) return f class LibraryLoader(object): darwin_not_found_error = "image not found" linux_not_found_error = "No such file or directory" def load_library(self, *names, **kwargs): '''Find and load a library. More than one name can be specified, they will be tried in order. Platform-specific library names (given as kwargs) are tried first. Raises ImportError if library is not found. ''' if 'framework' in kwargs and self.platform == 'darwin': return self.load_framework(kwargs['framework']) if not names: raise ImportError("No library name specified") platform_names = kwargs.get(self.platform, []) if type(platform_names) in (str, unicode): platform_names = [platform_names] elif type(platform_names) is tuple: platform_names = list(platform_names) if self.platform.startswith('linux'): for name in names: libname = self.find_library(name) platform_names.append(libname or 'lib%s.so' % name) platform_names.extend(names) for name in platform_names: try: lib = ctypes.cdll.LoadLibrary(name) if _debug_lib: print name if _debug_trace: lib = _TraceLibrary(lib) return lib except OSError, o: if ((self.platform == "win32" and o.winerror != 126) or (self.platform.startswith("linux") and self.linux_not_found_error not in o.args[0]) or (self.platform == "darwin" and self.darwin_not_found_error not in o.args[0])): print "Unexpected error loading library %s: %s" % (name, str(o)) raise path = self.find_library(name) if path: try: lib = ctypes.cdll.LoadLibrary(path) if _debug_lib: print path if _debug_trace: lib = _TraceLibrary(lib) return lib except OSError: pass raise ImportError('Library "%s" not found.' % names[0]) find_library = lambda self, name: ctypes.util.find_library(name) platform = pyglet.compat_platform # this is only for library loading, don't include it in pyglet.platform if platform == 'cygwin': platform = 'win32' def load_framework(self, path): raise RuntimeError("Can't load framework on this platform.") class MachOLibraryLoader(LibraryLoader): def __init__(self): if 'LD_LIBRARY_PATH' in os.environ: self.ld_library_path = os.environ['LD_LIBRARY_PATH'].split(':') else: self.ld_library_path = [] if _local_lib_paths: # search first for local libs self.ld_library_path = _local_lib_paths + self.ld_library_path os.environ['LD_LIBRARY_PATH'] = ':'.join(self.ld_library_path) if 'DYLD_LIBRARY_PATH' in os.environ: self.dyld_library_path = os.environ['DYLD_LIBRARY_PATH'].split(':') else: self.dyld_library_path = [] if 'DYLD_FALLBACK_LIBRARY_PATH' in os.environ: self.dyld_fallback_library_path = \ os.environ['DYLD_FALLBACK_LIBRARY_PATH'].split(':') else: self.dyld_fallback_library_path = [ os.path.expanduser('~/lib'), '/usr/local/lib', '/usr/lib'] def find_library(self, path): '''Implements the dylib search as specified in Apple documentation: http://developer.apple.com/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/DynamicLibraryUsageGuidelines.html Before commencing the standard search, the method first checks the bundle's ``Frameworks`` directory if the application is running within a bundle (OS X .app). ''' libname = os.path.basename(path) search_path = [] if '.' not in libname: libname = 'lib' + libname + '.dylib' # py2app support if (hasattr(sys, 'frozen') and sys.frozen == 'macosx_app' and 'RESOURCEPATH' in os.environ): search_path.append(os.path.join( os.environ['RESOURCEPATH'], '..', 'Frameworks', libname)) # pyinstaller.py sets sys.frozen to True, and puts dylibs in # Contents/MacOS, which path pyinstaller puts in sys._MEIPASS if (hasattr(sys, 'frozen') and hasattr(sys, '_MEIPASS') and sys.frozen == True and pyglet.compat_platform == 'darwin'): search_path.append(os.path.join(sys._MEIPASS, libname)) if '/' in path: search_path.extend( [os.path.join(p, libname) \ for p in self.dyld_library_path]) search_path.append(path) search_path.extend( [os.path.join(p, libname) \ for p in self.dyld_fallback_library_path]) else: search_path.extend( [os.path.join(p, libname) \ for p in self.ld_library_path]) search_path.extend( [os.path.join(p, libname) \ for p in self.dyld_library_path]) search_path.append(path) search_path.extend( [os.path.join(p, libname) \ for p in self.dyld_fallback_library_path]) for path in search_path: if os.path.exists(path): return path return None def find_framework(self, path): '''Implement runtime framework search as described by: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/FrameworkBinding.html ''' # e.g. path == '/System/Library/Frameworks/OpenGL.framework' # name == 'OpenGL' # return '/System/Library/Frameworks/OpenGL.framework/OpenGL' name = os.path.splitext(os.path.split(path)[1])[0] realpath = os.path.join(path, name) if os.path.exists(realpath): return realpath for dir in ('/Library/Frameworks', '/System/Library/Frameworks'): realpath = os.path.join(dir, '%s.framework' % name, name) if os.path.exists(realpath): return realpath return None def load_framework(self, path): realpath = self.find_framework(path) if realpath: lib = ctypes.cdll.LoadLibrary(realpath) if _debug_lib: print realpath if _debug_trace: lib = _TraceLibrary(lib) return lib raise ImportError("Can't find framework %s." % path) class LinuxLibraryLoader(LibraryLoader): _ld_so_cache = None _local_libs_cache = None def _find_libs(self, directories): cache = {} lib_re = re.compile('lib(.*)\.so(?:$|\.)') for dir in directories: try: for file in os.listdir(dir): match = lib_re.match(file) if match: # Index by filename path = os.path.join(dir, file) if file not in cache: cache[file] = path # Index by library name library = match.group(1) if library not in cache: cache[library] = path except OSError: pass return cache def _create_ld_so_cache(self): # Recreate search path followed by ld.so. This is going to be # slow to build, and incorrect (ld.so uses ld.so.cache, which may # not be up-to-date). Used only as fallback for distros without # /sbin/ldconfig. # # We assume the DT_RPATH and DT_RUNPATH binary sections are omitted. directories = [] try: directories.extend(os.environ['LD_LIBRARY_PATH'].split(':')) except KeyError: pass try: with open('/etc/ld.so.conf') as fid: directories.extend([dir.strip() for dir in fid]) except IOError: pass directories.extend(['/lib', '/usr/lib']) self._ld_so_cache = self._find_libs(directories) def find_library(self, path): # search first for local libs if _local_lib_paths: if not self._local_libs_cache: self._local_libs_cache = self._find_libs(_local_lib_paths) if path in self._local_libs_cache: return self._local_libs_cache[path] # ctypes tries ldconfig, gcc and objdump. If none of these are # present, we implement the ld-linux.so search path as described in # the man page. result = ctypes.util.find_library(path) if result: return result if self._ld_so_cache is None: self._create_ld_so_cache() return self._ld_so_cache.get(path) if pyglet.compat_platform == 'darwin': loader = MachOLibraryLoader() elif pyglet.compat_platform.startswith('linux'): loader = LinuxLibraryLoader() else: loader = LibraryLoader() load_library = loader.load_library
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Mouse constants and utilities for pyglet.window. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' def buttons_string(buttons): '''Return a string describing a set of active mouse buttons. Example:: >>> buttons_string(LEFT | RIGHT) 'LEFT|RIGHT' :Parameters: `buttons` : int Bitwise combination of mouse button constants. :rtype: str ''' button_names = [] if buttons & LEFT: button_names.append('LEFT') if buttons & MIDDLE: button_names.append('MIDDLE') if buttons & RIGHT: button_names.append('RIGHT') return '|'.join(button_names) # Symbolic names for the mouse buttons LEFT = 1 << 0 MIDDLE = 1 << 1 RIGHT = 1 << 2
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- __docformat__ = 'restructuredtext' __version__ = '$Id$' from ctypes import * import unicodedata import warnings import pyglet from pyglet.window import WindowException, NoSuchDisplayException, \ MouseCursorException, MouseCursor, \ DefaultMouseCursor, ImageMouseCursor, BaseWindow, _PlatformEventHandler, \ _ViewEventHandler from pyglet.window import key from pyglet.window import mouse from pyglet.event import EventDispatcher from pyglet.canvas.xlib import XlibCanvas from pyglet.libs.x11 import xlib from pyglet.libs.x11 import cursorfont from pyglet.compat import asbytes try: from pyglet.libs.x11 import xsync _have_xsync = True except: _have_xsync = False class mwmhints_t(Structure): _fields_ = [ ('flags', c_uint32), ('functions', c_uint32), ('decorations', c_uint32), ('input_mode', c_int32), ('status', c_uint32) ] # XXX: wraptypes can't parse the header this function is in yet XkbSetDetectableAutoRepeat = xlib._lib.XkbSetDetectableAutoRepeat XkbSetDetectableAutoRepeat.restype = c_int XkbSetDetectableAutoRepeat.argtypes = [POINTER(xlib.Display), c_int, POINTER(c_int)] _can_detect_autorepeat = None XA_CARDINAL = 6 # Xatom.h:14 # Do we have the November 2000 UTF8 extension? _have_utf8 = hasattr(xlib._lib, 'Xutf8TextListToTextProperty') # symbol,ctrl -> motion mapping _motion_map = { (key.UP, False): key.MOTION_UP, (key.RIGHT, False): key.MOTION_RIGHT, (key.DOWN, False): key.MOTION_DOWN, (key.LEFT, False): key.MOTION_LEFT, (key.RIGHT, True): key.MOTION_NEXT_WORD, (key.LEFT, True): key.MOTION_PREVIOUS_WORD, (key.HOME, False): key.MOTION_BEGINNING_OF_LINE, (key.END, False): key.MOTION_END_OF_LINE, (key.PAGEUP, False): key.MOTION_PREVIOUS_PAGE, (key.PAGEDOWN, False): key.MOTION_NEXT_PAGE, (key.HOME, True): key.MOTION_BEGINNING_OF_FILE, (key.END, True): key.MOTION_END_OF_FILE, (key.BACKSPACE, False): key.MOTION_BACKSPACE, (key.DELETE, False): key.MOTION_DELETE, } class XlibException(WindowException): '''An X11-specific exception. This exception is probably a programming error in pyglet.''' pass class XlibMouseCursor(MouseCursor): drawable = False def __init__(self, cursor): self.cursor = cursor # Platform event data is single item, so use platform event handler directly. XlibEventHandler = _PlatformEventHandler ViewEventHandler = _ViewEventHandler class XlibWindow(BaseWindow): _x_display = None # X display connection _x_screen_id = None # X screen index _x_ic = None # X input context _window = None # Xlib window handle _minimum_size = None _maximum_size = None _override_redirect = False _x = 0 _y = 0 # Last known window position _width = 0 _height = 0 # Last known window size _mouse_exclusive_client = None # x,y of "real" mouse during exclusive _mouse_buttons = [False] * 6 # State of each xlib button _keyboard_exclusive = False _active = True _applied_mouse_exclusive = False _applied_keyboard_exclusive = False _mapped = False _lost_context = False _lost_context_state = False _enable_xsync = False _current_sync_value = None _current_sync_valid = False _needs_resize = False # True when resize event has been received but not # dispatched _default_event_mask = (0x1ffffff & ~xlib.PointerMotionHintMask & ~xlib.ResizeRedirectMask & ~xlib.SubstructureNotifyMask) def __init__(self, *args, **kwargs): # Bind event handlers self._event_handlers = {} self._view_event_handlers = {} for name in self._platform_event_names: if not hasattr(self, name): continue func = getattr(self, name) for message in func._platform_event_data: if hasattr(func, '_view'): self._view_event_handlers[message] = func else: self._event_handlers[message] = func super(XlibWindow, self).__init__(*args, **kwargs) global _can_detect_autorepeat if _can_detect_autorepeat == None: supported_rtrn = c_int() _can_detect_autorepeat = XkbSetDetectableAutoRepeat(self.display._display, c_int(1), byref(supported_rtrn)) if _can_detect_autorepeat: self.pressed_keys = set() def _recreate(self, changes): # If flipping to/from fullscreen, need to recreate the window. (This # is the case with both override_redirect method and # _NET_WM_STATE_FULLSCREEN). # # A possible improvement could be to just hide the top window, # destroy the GLX window, and reshow it again when leaving fullscreen. # This would prevent the floating window from being moved by the # WM. if ('fullscreen' in changes or 'resizable' in changes): # clear out the GLX context self.context.detach() xlib.XDestroyWindow(self._x_display, self._window) del self.display._window_map[self._window] del self.display._window_map[self._view] self._window = None self._mapped = False # TODO: detect state loss only by examining context share. if 'context' in changes: self._lost_context = True self._lost_context_state = True self._create() def _create(self): # Unmap existing window if necessary while we fiddle with it. if self._window and self._mapped: self._unmap() self._x_display = self.display._display self._x_screen_id = self.display.x_screen # Create X window if not already existing. if not self._window: root = xlib.XRootWindow(self._x_display, self._x_screen_id) visual_info = self.config.get_visual_info() visual = visual_info.visual visual_id = xlib.XVisualIDFromVisual(visual) default_visual = xlib.XDefaultVisual( self._x_display, self._x_screen_id) default_visual_id = xlib.XVisualIDFromVisual(default_visual) window_attributes = xlib.XSetWindowAttributes() if visual_id != default_visual_id: window_attributes.colormap = xlib.XCreateColormap( self._x_display, root, visual, xlib.AllocNone) else: window_attributes.colormap = xlib.XDefaultColormap( self._x_display, self._x_screen_id) window_attributes.bit_gravity = xlib.StaticGravity # Issue 287: Compiz on Intel/Mesa doesn't draw window decoration # unless CWBackPixel is given in mask. Should have # no effect on other systems, so it's set # unconditionally. mask = xlib.CWColormap | xlib.CWBitGravity | xlib.CWBackPixel if self._fullscreen: width, height = self.screen.width, self.screen.height self._view_x = (width - self._width) // 2 self._view_y = (height - self._height) // 2 else: width, height = self._width, self._height self._view_x = self._view_y = 0 self._window = xlib.XCreateWindow(self._x_display, root, 0, 0, width, height, 0, visual_info.depth, xlib.InputOutput, visual, mask, byref(window_attributes)) self._view = xlib.XCreateWindow(self._x_display, self._window, self._view_x, self._view_y, self._width, self._height, 0, visual_info.depth, xlib.InputOutput, visual, mask, byref(window_attributes)); xlib.XMapWindow(self._x_display, self._view) xlib.XSelectInput( self._x_display, self._view, self._default_event_mask) self.display._window_map[self._window] = \ self.dispatch_platform_event self.display._window_map[self._view] = \ self.dispatch_platform_event_view self.canvas = XlibCanvas(self.display, self._view) self.context.attach(self.canvas) self.context.set_vsync(self._vsync) # XXX ? # Setting null background pixmap disables drawing the background, # preventing flicker while resizing (in theory). # # Issue 287: Compiz on Intel/Mesa doesn't draw window decoration if # this is called. As it doesn't seem to have any # effect anyway, it's just commented out. #xlib.XSetWindowBackgroundPixmap(self._x_display, self._window, 0) self._enable_xsync = (pyglet.options['xsync'] and self.display._enable_xsync and self.config.double_buffer) # Set supported protocols protocols = [] protocols.append(xlib.XInternAtom(self._x_display, asbytes('WM_DELETE_WINDOW'), False)) if self._enable_xsync: protocols.append(xlib.XInternAtom(self._x_display, asbytes('_NET_WM_SYNC_REQUEST'), False)) protocols = (c_ulong * len(protocols))(*protocols) xlib.XSetWMProtocols(self._x_display, self._window, protocols, len(protocols)) # Create window resize sync counter if self._enable_xsync: value = xsync.XSyncValue() self._sync_counter = xlib.XID( xsync.XSyncCreateCounter(self._x_display, value)) atom = xlib.XInternAtom(self._x_display, asbytes('_NET_WM_SYNC_REQUEST_COUNTER'), False) ptr = pointer(self._sync_counter) xlib.XChangeProperty(self._x_display, self._window, atom, XA_CARDINAL, 32, xlib.PropModeReplace, cast(ptr, POINTER(c_ubyte)), 1) # Set window attributes attributes = xlib.XSetWindowAttributes() attributes_mask = 0 self._override_redirect = False if self._fullscreen: if pyglet.options['xlib_fullscreen_override_redirect']: # Try not to use this any more, it causes problems; disabled # by default in favour of _NET_WM_STATE_FULLSCREEN. attributes.override_redirect = self._fullscreen attributes_mask |= xlib.CWOverrideRedirect self._override_redirect = True else: self._set_wm_state('_NET_WM_STATE_FULLSCREEN') if self._fullscreen: xlib.XMoveResizeWindow(self._x_display, self._window, self.screen.x, self.screen.y, self.screen.width, self.screen.height) else: xlib.XResizeWindow(self._x_display, self._window, self._width, self._height) xlib.XChangeWindowAttributes(self._x_display, self._window, attributes_mask, byref(attributes)) # Set style styles = { self.WINDOW_STYLE_DEFAULT: '_NET_WM_WINDOW_TYPE_NORMAL', self.WINDOW_STYLE_DIALOG: '_NET_WM_WINDOW_TYPE_DIALOG', self.WINDOW_STYLE_TOOL: '_NET_WM_WINDOW_TYPE_UTILITY', } if self._style in styles: self._set_atoms_property('_NET_WM_WINDOW_TYPE', (styles[self._style],)) elif self._style == self.WINDOW_STYLE_BORDERLESS: MWM_HINTS_DECORATIONS = 1 << 1 PROP_MWM_HINTS_ELEMENTS = 5 mwmhints = mwmhints_t() mwmhints.flags = MWM_HINTS_DECORATIONS mwmhints.decorations = 0 name = xlib.XInternAtom(self._x_display, asbytes('_MOTIF_WM_HINTS'), False) xlib.XChangeProperty(self._x_display, self._window, name, name, 32, xlib.PropModeReplace, cast(pointer(mwmhints), POINTER(c_ubyte)), PROP_MWM_HINTS_ELEMENTS) # Set resizeable if not self._resizable and not self._fullscreen: self.set_minimum_size(self._width, self._height) self.set_maximum_size(self._width, self._height) # Set caption self.set_caption(self._caption) # this is supported by some compositors (ie gnome-shell), and more to come # see: http://standards.freedesktop.org/wm-spec/wm-spec-latest.html#idp6357888 _NET_WM_BYPASS_COMPOSITOR_HINT_ON = c_ulong(int(self._fullscreen)) name = xlib.XInternAtom(self._x_display, asbytes('_NET_WM_BYPASS_COMPOSITOR'), False) ptr = pointer(_NET_WM_BYPASS_COMPOSITOR_HINT_ON) xlib.XChangeProperty(self._x_display, self._window, name, XA_CARDINAL, 32, xlib.PropModeReplace, cast(ptr, POINTER(c_ubyte)), 1) # Create input context. A good but very outdated reference for this # is http://www.sbin.org/doc/Xlib/chapt_11.html if _have_utf8 and not self._x_ic: if not self.display._x_im: xlib.XSetLocaleModifiers(asbytes('@im=none')) self.display._x_im = \ xlib.XOpenIM(self._x_display, None, None, None) xlib.XFlush(self._x_display); # Need to set argtypes on this function because it's vararg, # and ctypes guesses wrong. xlib.XCreateIC.argtypes = [xlib.XIM, c_char_p, c_int, c_char_p, xlib.Window, c_char_p, xlib.Window, c_void_p] self._x_ic = xlib.XCreateIC(self.display._x_im, asbytes('inputStyle'), xlib.XIMPreeditNothing|xlib.XIMStatusNothing, asbytes('clientWindow'), self._window, asbytes('focusWindow'), self._window, None) filter_events = c_ulong() xlib.XGetICValues(self._x_ic, 'filterEvents', byref(filter_events), None) self._default_event_mask |= filter_events.value xlib.XSetICFocus(self._x_ic) self.switch_to() if self._visible: self.set_visible(True) self.set_mouse_platform_visible() self._applied_mouse_exclusive = None self._update_exclusivity() def _map(self): if self._mapped: return # Map the window, wait for map event before continuing. xlib.XSelectInput( self._x_display, self._window, xlib.StructureNotifyMask) xlib.XMapRaised(self._x_display, self._window) e = xlib.XEvent() while True: xlib.XNextEvent(self._x_display, e) if e.type == xlib.ConfigureNotify: self._width = e.xconfigure.width self._height = e.xconfigure.height elif e.type == xlib.MapNotify: break xlib.XSelectInput( self._x_display, self._window, self._default_event_mask) self._mapped = True if self._override_redirect: # Possibly an override_redirect issue. self.activate() self._update_view_size() self.dispatch_event('on_resize', self._width, self._height) self.dispatch_event('on_show') self.dispatch_event('on_expose') def _unmap(self): if not self._mapped: return xlib.XSelectInput( self._x_display, self._window, xlib.StructureNotifyMask) xlib.XUnmapWindow(self._x_display, self._window) e = xlib.XEvent() while True: xlib.XNextEvent(self._x_display, e) if e.type == xlib.UnmapNotify: break xlib.XSelectInput( self._x_display, self._window, self._default_event_mask) self._mapped = False def _get_root(self): attributes = xlib.XWindowAttributes() xlib.XGetWindowAttributes(self._x_display, self._window, byref(attributes)) return attributes.root def _is_reparented(self): root = c_ulong() parent = c_ulong() children = pointer(c_ulong()) n_children = c_uint() xlib.XQueryTree(self._x_display, self._window, byref(root), byref(parent), byref(children), byref(n_children)) return root.value != parent.value def close(self): if not self._window: return self.context.destroy() self._unmap() if self._window: xlib.XDestroyWindow(self._x_display, self._window) del self.display._window_map[self._window] self._window = None if _have_utf8: xlib.XDestroyIC(self._x_ic) self._x_ic = None super(XlibWindow, self).close() def switch_to(self): if self.context: self.context.set_current() def flip(self): self.draw_mouse_cursor() # TODO canvas.flip? if self.context: self.context.flip() self._sync_resize() def set_vsync(self, vsync): if pyglet.options['vsync'] is not None: vsync = pyglet.options['vsync'] self._vsync = vsync self.context.set_vsync(vsync) def set_caption(self, caption): if caption is None: caption = '' self._caption = caption self._set_text_property('WM_NAME', caption, allow_utf8=False) self._set_text_property('WM_ICON_NAME', caption, allow_utf8=False) self._set_text_property('_NET_WM_NAME', caption) self._set_text_property('_NET_WM_ICON_NAME', caption) def get_caption(self): return self._caption def set_size(self, width, height): if self._fullscreen: raise WindowException('Cannot set size of fullscreen window.') self._width = width self._height = height if not self._resizable: self.set_minimum_size(width, height) self.set_maximum_size(width, height) xlib.XResizeWindow(self._x_display, self._window, width, height) self._update_view_size() self.dispatch_event('on_resize', width, height) def _update_view_size(self): xlib.XResizeWindow(self._x_display, self._view, self._width, self._height) def get_size(self): # XGetGeometry and XWindowAttributes seem to always return the # original size of the window, which is wrong after the user # has resized it. # XXX this is probably fixed now, with fix of resize. return self._width, self._height def set_location(self, x, y): if self._is_reparented(): # Assume the window manager has reparented our top-level window # only once, in which case attributes.x/y give the offset from # the frame to the content window. Better solution would be # to use _NET_FRAME_EXTENTS, where supported. attributes = xlib.XWindowAttributes() xlib.XGetWindowAttributes(self._x_display, self._window, byref(attributes)) # XXX at least under KDE's WM these attrs are both 0 x -= attributes.x y -= attributes.y xlib.XMoveWindow(self._x_display, self._window, x, y) def get_location(self): child = xlib.Window() x = c_int() y = c_int() xlib.XTranslateCoordinates(self._x_display, self._window, self._get_root(), 0, 0, byref(x), byref(y), byref(child)) return x.value, y.value def activate(self): xlib.XSetInputFocus(self._x_display, self._window, xlib.RevertToParent, xlib.CurrentTime) def set_visible(self, visible=True): if visible: self._map() else: self._unmap() self._visible = visible def set_minimum_size(self, width, height): self._minimum_size = width, height self._set_wm_normal_hints() def set_maximum_size(self, width, height): self._maximum_size = width, height self._set_wm_normal_hints() def minimize(self): xlib.XIconifyWindow(self._x_display, self._window, self._x_screen_id) def maximize(self): self._set_wm_state('_NET_WM_STATE_MAXIMIZED_HORZ', '_NET_WM_STATE_MAXIMIZED_VERT') def set_mouse_platform_visible(self, platform_visible=None): if not self._window: return if platform_visible is None: platform_visible = self._mouse_visible and \ not self._mouse_cursor.drawable if not platform_visible: # Hide pointer by creating an empty cursor black = xlib.XBlackPixel(self._x_display, self._x_screen_id) black = xlib.XColor() bmp = xlib.XCreateBitmapFromData(self._x_display, self._window, c_buffer(8), 8, 8) cursor = xlib.XCreatePixmapCursor(self._x_display, bmp, bmp, black, black, 0, 0) xlib.XDefineCursor(self._x_display, self._window, cursor) xlib.XFreeCursor(self._x_display, cursor) xlib.XFreePixmap(self._x_display, bmp) else: # Restore cursor if isinstance(self._mouse_cursor, XlibMouseCursor): xlib.XDefineCursor(self._x_display, self._window, self._mouse_cursor.cursor) else: xlib.XUndefineCursor(self._x_display, self._window) def set_mouse_position(self, x, y): xlib.XWarpPointer(self._x_display, 0, # src window self._window, # dst window 0, 0, # src x, y 0, 0, # src w, h x, self._height - y, ) def _update_exclusivity(self): mouse_exclusive = self._active and self._mouse_exclusive keyboard_exclusive = self._active and self._keyboard_exclusive if mouse_exclusive != self._applied_mouse_exclusive: if mouse_exclusive: self.set_mouse_platform_visible(False) # Restrict to client area xlib.XGrabPointer(self._x_display, self._window, True, 0, xlib.GrabModeAsync, xlib.GrabModeAsync, self._window, 0, xlib.CurrentTime) # Move pointer to center of window x = self._width // 2 y = self._height // 2 self._mouse_exclusive_client = x, y self.set_mouse_position(x, y) elif self._fullscreen and not self.screen._xinerama: # Restrict to fullscreen area (prevent viewport scrolling) self.set_mouse_position(0, 0) r = xlib.XGrabPointer(self._x_display, self._view, True, 0, xlib.GrabModeAsync, xlib.GrabModeAsync, self._view, 0, xlib.CurrentTime) if r: # Failed to grab, try again later self._applied_mouse_exclusive = None return self.set_mouse_platform_visible() else: # Unclip xlib.XUngrabPointer(self._x_display, xlib.CurrentTime) self.set_mouse_platform_visible() self._applied_mouse_exclusive = mouse_exclusive if keyboard_exclusive != self._applied_keyboard_exclusive: if keyboard_exclusive: xlib.XGrabKeyboard(self._x_display, self._window, False, xlib.GrabModeAsync, xlib.GrabModeAsync, xlib.CurrentTime) else: xlib.XUngrabKeyboard(self._x_display, xlib.CurrentTime) self._applied_keyboard_exclusive = keyboard_exclusive def set_exclusive_mouse(self, exclusive=True): if exclusive == self._mouse_exclusive: return self._mouse_exclusive = exclusive self._update_exclusivity() def set_exclusive_keyboard(self, exclusive=True): if exclusive == self._keyboard_exclusive: return self._keyboard_exclusive = exclusive self._update_exclusivity() def get_system_mouse_cursor(self, name): if name == self.CURSOR_DEFAULT: return DefaultMouseCursor() # NQR means default shape is not pretty... surely there is another # cursor font? cursor_shapes = { self.CURSOR_CROSSHAIR: cursorfont.XC_crosshair, self.CURSOR_HAND: cursorfont.XC_hand2, self.CURSOR_HELP: cursorfont.XC_question_arrow, # NQR self.CURSOR_NO: cursorfont.XC_pirate, # NQR self.CURSOR_SIZE: cursorfont.XC_fleur, self.CURSOR_SIZE_UP: cursorfont.XC_top_side, self.CURSOR_SIZE_UP_RIGHT: cursorfont.XC_top_right_corner, self.CURSOR_SIZE_RIGHT: cursorfont.XC_right_side, self.CURSOR_SIZE_DOWN_RIGHT: cursorfont.XC_bottom_right_corner, self.CURSOR_SIZE_DOWN: cursorfont.XC_bottom_side, self.CURSOR_SIZE_DOWN_LEFT: cursorfont.XC_bottom_left_corner, self.CURSOR_SIZE_LEFT: cursorfont.XC_left_side, self.CURSOR_SIZE_UP_LEFT: cursorfont.XC_top_left_corner, self.CURSOR_SIZE_UP_DOWN: cursorfont.XC_sb_v_double_arrow, self.CURSOR_SIZE_LEFT_RIGHT: cursorfont.XC_sb_h_double_arrow, self.CURSOR_TEXT: cursorfont.XC_xterm, self.CURSOR_WAIT: cursorfont.XC_watch, self.CURSOR_WAIT_ARROW: cursorfont.XC_watch, # NQR } if name not in cursor_shapes: raise MouseCursorException('Unknown cursor name "%s"' % name) cursor = xlib.XCreateFontCursor(self._x_display, cursor_shapes[name]) return XlibMouseCursor(cursor) def set_icon(self, *images): # Careful! XChangeProperty takes an array of long when data type # is 32-bit (but long can be 64 bit!), so pad high bytes of format if # necessary. import sys format = { ('little', 4): 'BGRA', ('little', 8): 'BGRAAAAA', ('big', 4): 'ARGB', ('big', 8): 'AAAAARGB' }[(sys.byteorder, sizeof(c_ulong))] data = asbytes('') for image in images: image = image.get_image_data() pitch = -(image.width * len(format)) s = c_buffer(sizeof(c_ulong) * 2) memmove(s, cast((c_ulong * 2)(image.width, image.height), POINTER(c_ubyte)), len(s)) data += s.raw + image.get_data(format, pitch) buffer = (c_ubyte * len(data))() memmove(buffer, data, len(data)) atom = xlib.XInternAtom(self._x_display, asbytes('_NET_WM_ICON'), False) xlib.XChangeProperty(self._x_display, self._window, atom, XA_CARDINAL, 32, xlib.PropModeReplace, buffer, len(data)//sizeof(c_ulong)) # Private utility def _set_wm_normal_hints(self): hints = xlib.XAllocSizeHints().contents if self._minimum_size: hints.flags |= xlib.PMinSize hints.min_width, hints.min_height = self._minimum_size if self._maximum_size: hints.flags |= xlib.PMaxSize hints.max_width, hints.max_height = self._maximum_size xlib.XSetWMNormalHints(self._x_display, self._window, byref(hints)) def _set_text_property(self, name, value, allow_utf8=True): atom = xlib.XInternAtom(self._x_display, asbytes(name), False) if not atom: raise XlibException('Undefined atom "%s"' % name) assert type(value) in (str, unicode) property = xlib.XTextProperty() if _have_utf8 and allow_utf8: buf = create_string_buffer(value.encode('utf8')) result = xlib.Xutf8TextListToTextProperty(self._x_display, cast(pointer(buf), c_char_p), 1, xlib.XUTF8StringStyle, byref(property)) if result < 0: raise XlibException('Could not create UTF8 text property') else: buf = create_string_buffer(value.encode('ascii', 'ignore')) result = xlib.XStringListToTextProperty( cast(pointer(buf), c_char_p), 1, byref(property)) if result < 0: raise XlibException('Could not create text property') xlib.XSetTextProperty(self._x_display, self._window, byref(property), atom) # XXX <rj> Xlib doesn't like us freeing this #xlib.XFree(property.value) def _set_atoms_property(self, name, values, mode=xlib.PropModeReplace): name_atom = xlib.XInternAtom(self._x_display, asbytes(name), False) atoms = [] for value in values: atoms.append(xlib.XInternAtom(self._x_display, asbytes(value), False)) atom_type = xlib.XInternAtom(self._x_display, asbytes('ATOM'), False) if len(atoms): atoms_ar = (xlib.Atom * len(atoms))(*atoms) xlib.XChangeProperty(self._x_display, self._window, name_atom, atom_type, 32, mode, cast(pointer(atoms_ar), POINTER(c_ubyte)), len(atoms)) else: xlib.XDeleteProperty(self._x_display, self._window, net_wm_state) def _set_wm_state(self, *states): # Set property net_wm_state = xlib.XInternAtom(self._x_display, asbytes('_NET_WM_STATE'), False) atoms = [] for state in states: atoms.append(xlib.XInternAtom(self._x_display, asbytes(state), False)) atom_type = xlib.XInternAtom(self._x_display, asbytes('ATOM'), False) if len(atoms): atoms_ar = (xlib.Atom * len(atoms))(*atoms) xlib.XChangeProperty(self._x_display, self._window, net_wm_state, atom_type, 32, xlib.PropModePrepend, cast(pointer(atoms_ar), POINTER(c_ubyte)), len(atoms)) else: xlib.XDeleteProperty(self._x_display, self._window, net_wm_state) # Nudge the WM e = xlib.XEvent() e.xclient.type = xlib.ClientMessage e.xclient.message_type = net_wm_state e.xclient.display = cast(self._x_display, POINTER(xlib.Display)) e.xclient.window = self._window e.xclient.format = 32 e.xclient.data.l[0] = xlib.PropModePrepend for i, atom in enumerate(atoms): e.xclient.data.l[i + 1] = atom xlib.XSendEvent(self._x_display, self._get_root(), False, xlib.SubstructureRedirectMask, byref(e)) # Event handling def dispatch_events(self): self.dispatch_pending_events() self._allow_dispatch_event = True e = xlib.XEvent() # Cache these in case window is closed from an event handler _x_display = self._x_display _window = self._window _view = self._view # Check for the events specific to this window while xlib.XCheckWindowEvent(_x_display, _window, 0x1ffffff, byref(e)): # Key events are filtered by the xlib window event # handler so they get a shot at the prefiltered event. if e.xany.type not in (xlib.KeyPress, xlib.KeyRelease): if xlib.XFilterEvent(e, 0): continue self.dispatch_platform_event(e) # Check for the events specific to this view while xlib.XCheckWindowEvent(_x_display, _view, 0x1ffffff, byref(e)): # Key events are filtered by the xlib window event # handler so they get a shot at the prefiltered event. if e.xany.type not in (xlib.KeyPress, xlib.KeyRelease): if xlib.XFilterEvent(e, 0): continue self.dispatch_platform_event_view(e) # Generic events for this window (the window close event). while xlib.XCheckTypedWindowEvent(_x_display, _window, xlib.ClientMessage, byref(e)): self.dispatch_platform_event(e) if self._needs_resize: self.dispatch_event('on_resize', self._width, self._height) self.dispatch_event('on_expose') self._needs_resize = False self._allow_dispatch_event = False def dispatch_pending_events(self): while self._event_queue: EventDispatcher.dispatch_event(self, *self._event_queue.pop(0)) # Dispatch any context-related events if self._lost_context: self._lost_context = False EventDispatcher.dispatch_event(self, 'on_context_lost') if self._lost_context_state: self._lost_context_state = False EventDispatcher.dispatch_event(self, 'on_context_state_lost') def dispatch_platform_event(self, e): if self._applied_mouse_exclusive is None: self._update_exclusivity() event_handler = self._event_handlers.get(e.type) if event_handler: event_handler(e) def dispatch_platform_event_view(self, e): event_handler = self._view_event_handlers.get(e.type) if event_handler: event_handler(e) @staticmethod def _translate_modifiers(state): modifiers = 0 if state & xlib.ShiftMask: modifiers |= key.MOD_SHIFT if state & xlib.ControlMask: modifiers |= key.MOD_CTRL if state & xlib.LockMask: modifiers |= key.MOD_CAPSLOCK if state & xlib.Mod1Mask: modifiers |= key.MOD_ALT if state & xlib.Mod2Mask: modifiers |= key.MOD_NUMLOCK if state & xlib.Mod4Mask: modifiers |= key.MOD_WINDOWS if state & xlib.Mod5Mask: modifiers |= key.MOD_SCROLLLOCK return modifiers # Event handlers ''' def _event_symbol(self, event): # pyglet.self.key keysymbols are identical to X11 keysymbols, no # need to map the keysymbol. symbol = xlib.XKeycodeToKeysym(self._x_display, event.xkey.keycode, 0) if symbol == 0: # XIM event return None elif symbol not in key._key_names.keys(): symbol = key.user_key(event.xkey.keycode) return symbol ''' def _event_text_symbol(self, ev): text = None symbol = xlib.KeySym() buffer = create_string_buffer(128) # Look up raw keysym before XIM filters it (default for keypress and # keyrelease) count = xlib.XLookupString(ev.xkey, buffer, len(buffer) - 1, byref(symbol), None) # Give XIM a shot filtered = xlib.XFilterEvent(ev, ev.xany.window) if ev.type == xlib.KeyPress and not filtered: status = c_int() if _have_utf8: encoding = 'utf8' count = xlib.Xutf8LookupString(self._x_ic, ev.xkey, buffer, len(buffer) - 1, byref(symbol), byref(status)) if status.value == xlib.XBufferOverflow: raise NotImplementedError('TODO: XIM buffer resize') else: encoding = 'ascii' count = xlib.XLookupString(ev.xkey, buffer, len(buffer) - 1, byref(symbol), None) if count: status.value = xlib.XLookupBoth if status.value & (xlib.XLookupChars | xlib.XLookupBoth): text = buffer.value[:count].decode(encoding) # Don't treat Unicode command codepoints as text, except Return. if text and unicodedata.category(text) == 'Cc' and text != '\r': text = None symbol = symbol.value # If the event is a XIM filtered event, the keysym will be virtual # (e.g., aacute instead of A after a dead key). Drop it, we don't # want these kind of key events. if ev.xkey.keycode == 0 and not filtered: symbol = None # pyglet.self.key keysymbols are identical to X11 keysymbols, no # need to map the keysymbol. For keysyms outside the pyglet set, map # raw key code to a user key. if symbol and symbol not in key._key_names and ev.xkey.keycode: # Issue 353: Symbol is uppercase when shift key held down. try: symbol = ord(unichr(symbol).lower()) except ValueError: # Not a valid unichr, use the keycode symbol = key.user_key(ev.xkey.keycode) else: # If still not recognised, use the keycode if symbol not in key._key_names: symbol = key.user_key(ev.xkey.keycode) if filtered: # The event was filtered, text must be ignored, but the symbol is # still good. return None, symbol return text, symbol def _event_text_motion(self, symbol, modifiers): if modifiers & key.MOD_ALT: return None ctrl = modifiers & key.MOD_CTRL != 0 return _motion_map.get((symbol, ctrl), None) @ViewEventHandler @XlibEventHandler(xlib.KeyPress) @XlibEventHandler(xlib.KeyRelease) def _event_key_view(self, ev): # Try to detect autorepeat ourselves if the server doesn't support it # XXX: Doesn't always work, better off letting the server do it global _can_detect_autorepeat if not _can_detect_autorepeat and ev.type == xlib.KeyRelease: # Look in the queue for a matching KeyPress with same timestamp, # indicating an auto-repeat rather than actual key event. saved = [] while True: auto_event = xlib.XEvent() result = xlib.XCheckWindowEvent(self._x_display, self._window, xlib.KeyPress|xlib.KeyRelease, byref(auto_event)) if not result: break saved.append(auto_event) if auto_event.type == xlib.KeyRelease: # just save this off for restoration back to the queue continue if ev.xkey.keycode == auto_event.xkey.keycode: # Found a key repeat: dispatch EVENT_TEXT* event text, symbol = self._event_text_symbol(auto_event) modifiers = self._translate_modifiers(ev.xkey.state) modifiers_ctrl = modifiers & (key.MOD_CTRL | key.MOD_ALT) motion = self._event_text_motion(symbol, modifiers) if motion: if modifiers & key.MOD_SHIFT: self.dispatch_event( 'on_text_motion_select', motion) else: self.dispatch_event('on_text_motion', motion) elif text and not modifiers_ctrl: self.dispatch_event('on_text', text) ditched = saved.pop() for auto_event in reversed(saved): xlib.XPutBackEvent(self._x_display, byref(auto_event)) return else: # Key code of press did not match, therefore no repeating # is going on, stop searching. break # Whoops, put the events back, it's for real. for auto_event in reversed(saved): xlib.XPutBackEvent(self._x_display, byref(auto_event)) text, symbol = self._event_text_symbol(ev) modifiers = self._translate_modifiers(ev.xkey.state) modifiers_ctrl = modifiers & (key.MOD_CTRL | key.MOD_ALT) motion = self._event_text_motion(symbol, modifiers) if ev.type == xlib.KeyPress: if symbol and (not _can_detect_autorepeat or symbol not in self.pressed_keys): self.dispatch_event('on_key_press', symbol, modifiers) if _can_detect_autorepeat: self.pressed_keys.add(symbol) if motion: if modifiers & key.MOD_SHIFT: self.dispatch_event('on_text_motion_select', motion) else: self.dispatch_event('on_text_motion', motion) elif text and not modifiers_ctrl: self.dispatch_event('on_text', text) elif ev.type == xlib.KeyRelease: if symbol: self.dispatch_event('on_key_release', symbol, modifiers) if _can_detect_autorepeat and symbol in self.pressed_keys: self.pressed_keys.remove(symbol) @XlibEventHandler(xlib.KeyPress) @XlibEventHandler(xlib.KeyRelease) def _event_key(self, ev): return self._event_key_view(ev) @ViewEventHandler @XlibEventHandler(xlib.MotionNotify) def _event_motionnotify_view(self, ev): x = ev.xmotion.x y = self.height - ev.xmotion.y if self._mouse_in_window: dx = x - self._mouse_x dy = y - self._mouse_y else: dx = dy = 0 if self._applied_mouse_exclusive and \ (ev.xmotion.x, ev.xmotion.y) == self._mouse_exclusive_client: # Ignore events caused by XWarpPointer self._mouse_x = x self._mouse_y = y return if self._applied_mouse_exclusive: # Reset pointer position ex, ey = self._mouse_exclusive_client xlib.XWarpPointer(self._x_display, 0, self._window, 0, 0, 0, 0, ex, ey) self._mouse_x = x self._mouse_y = y self._mouse_in_window = True buttons = 0 if ev.xmotion.state & xlib.Button1MotionMask: buttons |= mouse.LEFT if ev.xmotion.state & xlib.Button2MotionMask: buttons |= mouse.MIDDLE if ev.xmotion.state & xlib.Button3MotionMask: buttons |= mouse.RIGHT if buttons: # Drag event modifiers = self._translate_modifiers(ev.xmotion.state) self.dispatch_event('on_mouse_drag', x, y, dx, dy, buttons, modifiers) else: # Motion event self.dispatch_event('on_mouse_motion', x, y, dx, dy) @XlibEventHandler(xlib.MotionNotify) def _event_motionnotify(self, ev): # Window motion looks for drags that are outside the view but within # the window. buttons = 0 if ev.xmotion.state & xlib.Button1MotionMask: buttons |= mouse.LEFT if ev.xmotion.state & xlib.Button2MotionMask: buttons |= mouse.MIDDLE if ev.xmotion.state & xlib.Button3MotionMask: buttons |= mouse.RIGHT if buttons: # Drag event x = ev.xmotion.x - self._view_x y = self._height - (ev.xmotion.y - self._view_y) if self._mouse_in_window: dx = x - self._mouse_x dy = y - self._mouse_y else: dx = dy = 0 self._mouse_x = x self._mouse_y = y modifiers = self._translate_modifiers(ev.xmotion.state) self.dispatch_event('on_mouse_drag', x, y, dx, dy, buttons, modifiers) @XlibEventHandler(xlib.ClientMessage) def _event_clientmessage(self, ev): atom = ev.xclient.data.l[0] if atom == xlib.XInternAtom(ev.xclient.display, asbytes('WM_DELETE_WINDOW'), False): self.dispatch_event('on_close') elif (self._enable_xsync and atom == xlib.XInternAtom(ev.xclient.display, asbytes('_NET_WM_SYNC_REQUEST'), False)): lo = ev.xclient.data.l[2] hi = ev.xclient.data.l[3] self._current_sync_value = xsync.XSyncValue(hi, lo) def _sync_resize(self): if self._enable_xsync and self._current_sync_valid: if xsync.XSyncValueIsZero(self._current_sync_value): self._current_sync_valid = False return xsync.XSyncSetCounter(self._x_display, self._sync_counter, self._current_sync_value) self._current_sync_value = None self._current_sync_valid = False @ViewEventHandler @XlibEventHandler(xlib.ButtonPress) @XlibEventHandler(xlib.ButtonRelease) def _event_button(self, ev): x = ev.xbutton.x y = self.height - ev.xbutton.y button = 1 << (ev.xbutton.button - 1) # 1, 2, 3 -> 1, 2, 4 modifiers = self._translate_modifiers(ev.xbutton.state) if ev.type == xlib.ButtonPress: # override_redirect issue: manually activate this window if # fullscreen. if self._override_redirect and not self._active: self.activate() if ev.xbutton.button == 4: self.dispatch_event('on_mouse_scroll', x, y, 0, 1) elif ev.xbutton.button == 5: self.dispatch_event('on_mouse_scroll', x, y, 0, -1) elif ev.xbutton.button < len(self._mouse_buttons): self._mouse_buttons[ev.xbutton.button] = True self.dispatch_event('on_mouse_press', x, y, button, modifiers) else: if ev.xbutton.button < 4: self._mouse_buttons[ev.xbutton.button] = False self.dispatch_event('on_mouse_release', x, y, button, modifiers) @ViewEventHandler @XlibEventHandler(xlib.Expose) def _event_expose(self, ev): # Ignore all expose events except the last one. We could be told # about exposure rects - but I don't see the point since we're # working with OpenGL and we'll just redraw the whole scene. if ev.xexpose.count > 0: return self.dispatch_event('on_expose') @ViewEventHandler @XlibEventHandler(xlib.EnterNotify) def _event_enternotify(self, ev): # figure active mouse buttons # XXX ignore modifier state? state = ev.xcrossing.state self._mouse_buttons[1] = state & xlib.Button1Mask self._mouse_buttons[2] = state & xlib.Button2Mask self._mouse_buttons[3] = state & xlib.Button3Mask self._mouse_buttons[4] = state & xlib.Button4Mask self._mouse_buttons[5] = state & xlib.Button5Mask # mouse position x = self._mouse_x = ev.xcrossing.x y = self._mouse_y = self.height - ev.xcrossing.y self._mouse_in_window = True # XXX there may be more we could do here self.dispatch_event('on_mouse_enter', x, y) @ViewEventHandler @XlibEventHandler(xlib.LeaveNotify) def _event_leavenotify(self, ev): x = self._mouse_x = ev.xcrossing.x y = self._mouse_y = self.height - ev.xcrossing.y self._mouse_in_window = False self.dispatch_event('on_mouse_leave', x, y) @XlibEventHandler(xlib.ConfigureNotify) def _event_configurenotify(self, ev): if self._enable_xsync and self._current_sync_value: self._current_sync_valid = True if self._fullscreen: return self.switch_to() w, h = ev.xconfigure.width, ev.xconfigure.height x, y = ev.xconfigure.x, ev.xconfigure.y if self._width != w or self._height != h: self._width = w self._height = h self._update_view_size() self._needs_resize = True if self._x != x or self._y != y: self.dispatch_event('on_move', x, y) self._x = x self._y = y @XlibEventHandler(xlib.FocusIn) def _event_focusin(self, ev): self._active = True self._update_exclusivity() self.dispatch_event('on_activate') xlib.XSetICFocus(self._x_ic) @XlibEventHandler(xlib.FocusOut) def _event_focusout(self, ev): self._active = False self._update_exclusivity() self.dispatch_event('on_deactivate') xlib.XUnsetICFocus(self._x_ic) @XlibEventHandler(xlib.MapNotify) def _event_mapnotify(self, ev): self._mapped = True self.dispatch_event('on_show') self._update_exclusivity() @XlibEventHandler(xlib.UnmapNotify) def _event_unmapnotify(self, ev): self._mapped = False self.dispatch_event('on_hide')
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from ctypes import * import os.path import unicodedata import warnings import pyglet from pyglet.window import WindowException, \ BaseWindow, MouseCursor, DefaultMouseCursor, _PlatformEventHandler from pyglet.window import key from pyglet.window import mouse from pyglet.window import event from pyglet.canvas.carbon import CarbonCanvas from pyglet.libs.darwin import * from pyglet.libs.darwin import _oscheck from pyglet.libs.darwin.quartzkey import keymap, charmap from pyglet.event import EventDispatcher # Map symbol,modifiers -> motion # Determined by experiment with TextEdit.app _motion_map = { (key.UP, False): key.MOTION_UP, (key.RIGHT, False): key.MOTION_RIGHT, (key.DOWN, False): key.MOTION_DOWN, (key.LEFT, False): key.MOTION_LEFT, (key.LEFT, key.MOD_OPTION): key.MOTION_PREVIOUS_WORD, (key.RIGHT, key.MOD_OPTION): key.MOTION_NEXT_WORD, (key.LEFT, key.MOD_COMMAND): key.MOTION_BEGINNING_OF_LINE, (key.RIGHT, key.MOD_COMMAND): key.MOTION_END_OF_LINE, (key.PAGEUP, False): key.MOTION_PREVIOUS_PAGE, (key.PAGEDOWN, False): key.MOTION_NEXT_PAGE, (key.HOME, False): key.MOTION_BEGINNING_OF_FILE, (key.END, False): key.MOTION_END_OF_FILE, (key.UP, key.MOD_COMMAND): key.MOTION_BEGINNING_OF_FILE, (key.DOWN, key.MOD_COMMAND): key.MOTION_END_OF_FILE, (key.BACKSPACE, False): key.MOTION_BACKSPACE, (key.DELETE, False): key.MOTION_DELETE, } class CarbonMouseCursor(MouseCursor): drawable = False def __init__(self, theme): self.theme = theme def CarbonEventHandler(event_class, event_kind): return _PlatformEventHandler((event_class, event_kind)) class CarbonWindow(BaseWindow): _window = None # Carbon WindowRef # Window properties _minimum_size = None _maximum_size = None _event_dispatcher = None _current_modifiers = 0 _mapped_modifers = 0 _carbon_event_handlers = [] _carbon_event_handler_refs = [] _track_ref = 0 _track_region = None _mouse_exclusive = False _mouse_platform_visible = True _mouse_ignore_motion = False _mouse_button_state = 0 def _recreate(self, changes): # We can't destroy the window while event handlers are active, # otherwise the (OS X) event dispatcher gets lost and segfaults. # # Defer actual recreation until dispatch_events next finishes. from pyglet import app app.platform_event_loop.post_event(self, 'on_recreate_immediate', changes) def on_recreate_immediate(self, changes): # The actual _recreate function. if ('context' in changes): self.context.detach() self._create() def _create(self): if self._window: # The window is about to be recreated; destroy everything # associated with the old window, then the window itself. self._remove_track_region() self._remove_event_handlers() self.context.detach() self.canvas = None carbon.DisposeWindow(self._window) self._window = None self._window = WindowRef() if self._fullscreen: rect = Rect() rect.left = 0 rect.top = 0 rect.right = self.screen.width rect.bottom = self.screen.height r = carbon.CreateNewWindow(kSimpleWindowClass, kWindowNoAttributes, byref(rect), byref(self._window)) _oscheck(r) # Set window level to shield level level = carbon.CGShieldingWindowLevel() WindowGroupRef = c_void_p group = WindowGroupRef() _oscheck(carbon.CreateWindowGroup(0, byref(group))) _oscheck(carbon.SetWindowGroup(self._window, group)) _oscheck(carbon.SetWindowGroupLevel(group, level)) # Set black background color = RGBColor(0, 0, 0) _oscheck(carbon.SetWindowContentColor(self._window, byref(color))) self._mouse_in_window = True self.dispatch_event('on_resize', self._width, self._height) self.dispatch_event('on_show') self.dispatch_event('on_expose') self._view_x = (self.screen.width - self._width) // 2 self._view_y = (self.screen.height - self._height) // 2 self.canvas = CarbonCanvas(self.display, self.screen, carbon.GetWindowPort(self._window)) self.canvas.bounds = (self._view_x, self._view_y, self._width, self._height) else: # Create floating window rect = Rect() location = None # TODO if location is not None: rect.left = location[0] rect.top = location[1] else: rect.top = rect.left = 0 rect.right = rect.left + self._width rect.bottom = rect.top + self._height styles = { self.WINDOW_STYLE_DEFAULT: (kDocumentWindowClass, kWindowCloseBoxAttribute | kWindowCollapseBoxAttribute), self.WINDOW_STYLE_DIALOG: (kDocumentWindowClass, kWindowCloseBoxAttribute), self.WINDOW_STYLE_TOOL: (kUtilityWindowClass, kWindowCloseBoxAttribute), self.WINDOW_STYLE_BORDERLESS: (kSimpleWindowClass, kWindowNoAttributes) } window_class, window_attributes = \ styles.get(self._style, kDocumentWindowClass) if self._resizable: window_attributes |= (kWindowFullZoomAttribute | kWindowLiveResizeAttribute | kWindowResizableAttribute) r = carbon.CreateNewWindow(window_class, window_attributes, byref(rect), byref(self._window)) _oscheck(r) if location is None: carbon.RepositionWindow(self._window, c_void_p(), kWindowCascadeOnMainScreen) self.canvas = CarbonCanvas(self.display, self.screen, carbon.GetWindowPort(self._window)) self._view_x = self._view_y = 0 self.context.attach(self.canvas) self.set_caption(self._caption) # Get initial state self._event_dispatcher = carbon.GetEventDispatcherTarget() self._current_modifiers = carbon.GetCurrentKeyModifiers().value self._mapped_modifiers = self._map_modifiers(self._current_modifiers) # (re)install Carbon event handlers self._install_event_handlers() self._create_track_region() self.switch_to() # XXX self.set_vsync(self._vsync) if self._visible: self.set_visible(True) def _create_track_region(self): self._remove_track_region() # Create a tracking region for the content part of the window # to receive enter/leave events. track_id = MouseTrackingRegionID() track_id.signature = DEFAULT_CREATOR_CODE track_id.id = 1 self._track_ref = MouseTrackingRef() self._track_region = carbon.NewRgn() if self._fullscreen: carbon.SetRectRgn(self._track_region, self._view_x, self._view_y, self._view_x + self._width, self._view_y + self._height) options = kMouseTrackingOptionsGlobalClip else: carbon.GetWindowRegion(self._window, kWindowContentRgn, self._track_region) options = kMouseTrackingOptionsGlobalClip carbon.CreateMouseTrackingRegion(self._window, self._track_region, None, options, track_id, None, None, byref(self._track_ref)) def _remove_track_region(self): if self._track_region: carbon.ReleaseMouseTrackingRegion(self._track_region) self._track_region = None def close(self): super(CarbonWindow, self).close() self._remove_event_handlers() self._remove_track_region() # Restore cursor visibility self.set_mouse_platform_visible(True) self.set_exclusive_mouse(False) if self._window: carbon.DisposeWindow(self._window) self._window = None def switch_to(self): self.context.set_current() ''' agl.aglSetCurrentContext(self._agl_context) self._context.set_current() _aglcheck() # XXX TODO transpose gl[u]_info to gl.Context.attach gl_info.set_active_context() glu_info.set_active_context() ''' def flip(self): self.draw_mouse_cursor() if self.context: self.context.flip() def _get_vsync(self): if self.context: return self.context.get_vsync() return self._vsync vsync = property(_get_vsync) # overrides BaseWindow property def set_vsync(self, vsync): if pyglet.options['vsync'] is not None: vsync = pyglet.options['vsync'] self._vsync = vsync # _recreate depends on this if self.context: self.context.set_vsync(vsync) def dispatch_events(self): from pyglet import app app.platform_event_loop.dispatch_posted_events() self._allow_dispatch_event = True while self._event_queue: EventDispatcher.dispatch_event(self, *self._event_queue.pop(0)) e = EventRef() result = carbon.ReceiveNextEvent(0, c_void_p(), 0, True, byref(e)) while result == noErr: carbon.SendEventToEventTarget(e, self._event_dispatcher) carbon.ReleaseEvent(e) result = carbon.ReceiveNextEvent(0, c_void_p(), 0, True, byref(e)) self._allow_dispatch_event = False # Return value from ReceiveNextEvent can be ignored if not # noErr; we check here only to look for new bugs. # eventLoopQuitErr: the inner event loop was quit, see # http://lists.apple.com/archives/Carbon-dev/2006/Jun/msg00850.html # Can occur when mixing with other toolkits, e.g. Tk. # Fixes issue 180. if result not in (eventLoopTimedOutErr, eventLoopQuitErr): raise 'Error %d' % result def dispatch_pending_events(self): while self._event_queue: EventDispatcher.dispatch_event(self, *self._event_queue.pop(0)) def set_caption(self, caption): self._caption = caption s = create_cfstring(caption) carbon.SetWindowTitleWithCFString(self._window, s) carbon.CFRelease(s) def set_location(self, x, y): rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) rect.right += x - rect.left rect.bottom += y - rect.top rect.left = x rect.top = y carbon.SetWindowBounds(self._window, kWindowContentRgn, byref(rect)) def get_location(self): rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) return rect.left, rect.top def set_size(self, width, height): if self._fullscreen: raise WindowException('Cannot set size of fullscreen window.') rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) rect.right = rect.left + width rect.bottom = rect.top + height carbon.SetWindowBounds(self._window, kWindowContentRgn, byref(rect)) self._width = width self._height = height self.dispatch_event('on_resize', width, height) self.dispatch_event('on_expose') def get_size(self): if self._fullscreen: return self._width, self._height rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) return rect.right - rect.left, rect.bottom - rect.top def set_minimum_size(self, width, height): self._minimum_size = (width, height) minimum = HISize() minimum.width = width minimum.height = height if self._maximum_size: maximum = HISize() maximum.width, maximum.height = self._maximum_size maximum = byref(maximum) else: maximum = None carbon.SetWindowResizeLimits(self._window, byref(minimum), maximum) def set_maximum_size(self, width, height): self._maximum_size = (width, height) maximum = HISize() maximum.width = width maximum.height = height if self._minimum_size: minimum = HISize() minimum.width, minimum.height = self._minimum_size minimum = byref(minimum) else: minimum = None carbon.SetWindowResizeLimits(self._window, minimum, byref(maximum)) def activate(self): carbon.ActivateWindow(self._window, 1) # Also make the application the "front" application. TODO # maybe don't bring forward all of the application's windows? psn = ProcessSerialNumber() psn.highLongOfPSN = 0 psn.lowLongOfPSN = kCurrentProcess carbon.SetFrontProcess(byref(psn)) def set_visible(self, visible=True): self._visible = visible if visible: self.dispatch_event('on_resize', self._width, self._height) self.dispatch_event('on_show') self.dispatch_event('on_expose') carbon.ShowWindow(self._window) else: carbon.HideWindow(self._window) def minimize(self): self._mouse_in_window = False self.set_mouse_platform_visible() carbon.CollapseWindow(self._window, True) def maximize(self): # Maximum "safe" value, gets trimmed to screen size automatically. p = Point() p.v, p.h = 16000,16000 if not carbon.IsWindowInStandardState(self._window, byref(p), None): carbon.ZoomWindowIdeal(self._window, inZoomOut, byref(p)) def set_mouse_platform_visible(self, platform_visible=None): if platform_visible is None: platform_visible = self._mouse_visible and \ not self._mouse_exclusive and \ not self._mouse_cursor.drawable if not self._mouse_in_window: platform_visible = True if self._mouse_in_window and \ isinstance(self._mouse_cursor, CarbonMouseCursor): carbon.SetThemeCursor(self._mouse_cursor.theme) else: carbon.SetThemeCursor(kThemeArrowCursor) if self._mouse_platform_visible == platform_visible: return if platform_visible: carbon.ShowCursor() else: carbon.HideCursor() self._mouse_platform_visible = platform_visible def set_exclusive_mouse(self, exclusive=True): self._mouse_exclusive = exclusive if exclusive: # Move mouse to center of window rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) x = (rect.right + rect.left) / 2 y = (rect.bottom + rect.top) / 2 # Skip the next motion event, which would return a large delta. self._mouse_ignore_motion = True self.set_mouse_position(x, y, absolute=True) carbon.CGAssociateMouseAndMouseCursorPosition(False) else: carbon.CGAssociateMouseAndMouseCursorPosition(True) self.set_mouse_platform_visible() def set_mouse_position(self, x, y, absolute=False): point = CGPoint() if absolute: point.x = x point.y = y else: rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) point.x = x + rect.left point.y = rect.top + (rect.bottom - rect.top) - y carbon.CGWarpMouseCursorPosition(point) def set_exclusive_keyboard(self, exclusive=True): if exclusive: # Note: power switch can also be disabled, with # kUIOptionDisableSessionTerminate. That seems # a little extreme though. carbon.SetSystemUIMode(kUIModeAllHidden, (kUIOptionDisableAppleMenu | kUIOptionDisableProcessSwitch | kUIOptionDisableForceQuit | kUIOptionDisableHide)) else: carbon.SetSystemUIMode(kUIModeNormal, 0) def get_system_mouse_cursor(self, name): if name == self.CURSOR_DEFAULT: return DefaultMouseCursor() themes = { self.CURSOR_CROSSHAIR: kThemeCrossCursor, self.CURSOR_HAND: kThemePointingHandCursor, self.CURSOR_HELP: kThemeArrowCursor, self.CURSOR_NO: kThemeNotAllowedCursor, self.CURSOR_SIZE: kThemeArrowCursor, self.CURSOR_SIZE_UP: kThemeResizeUpCursor, self.CURSOR_SIZE_UP_RIGHT: kThemeArrowCursor, self.CURSOR_SIZE_RIGHT: kThemeResizeRightCursor, self.CURSOR_SIZE_DOWN_RIGHT: kThemeArrowCursor, self.CURSOR_SIZE_DOWN: kThemeResizeDownCursor, self.CURSOR_SIZE_DOWN_LEFT: kThemeArrowCursor, self.CURSOR_SIZE_LEFT: kThemeResizeLeftCursor, self.CURSOR_SIZE_UP_LEFT: kThemeArrowCursor, self.CURSOR_SIZE_UP_DOWN: kThemeResizeUpDownCursor, self.CURSOR_SIZE_LEFT_RIGHT: kThemeResizeLeftRightCursor, self.CURSOR_TEXT: kThemeIBeamCursor, self.CURSOR_WAIT: kThemeWatchCursor, self.CURSOR_WAIT_ARROW: kThemeWatchCursor, } if name not in themes: raise RuntimeError('Unknown cursor name "%s"' % name) return CarbonMouseCursor(themes[name]) def set_icon(self, *images): # Only use the biggest image image = images[0] size = image.width * image.height for img in images: if img.width * img.height > size: size = img.width * img.height image = img image = image.get_image_data() format = 'ARGB' pitch = -len(format) * image.width data = image.get_data(format, pitch) provider = carbon.CGDataProviderCreateWithData( None, data, len(data), None) colorspace = carbon.CGColorSpaceCreateDeviceRGB() cgi = carbon.CGImageCreate( image.width, image.height, 8, 32, -pitch, colorspace, kCGImageAlphaFirst, provider, None, True, kCGRenderingIntentDefault) carbon.SetApplicationDockTileImage(cgi) carbon.CGDataProviderRelease(provider) carbon.CGColorSpaceRelease(colorspace) # Non-public utilities def _update_drawable(self): if self.context: self.context.update_geometry() # Need a redraw self.dispatch_event('on_expose') def _update_track_region(self): if not self._fullscreen: carbon.GetWindowRegion(self._window, kWindowContentRgn, self._track_region) carbon.ChangeMouseTrackingRegion(self._track_ref, self._track_region, None) def _install_event_handlers(self): self._remove_event_handlers() if self._fullscreen: target = carbon.GetApplicationEventTarget() else: target = carbon.GetWindowEventTarget(self._window) carbon.InstallStandardEventHandler(target) self._carbon_event_handlers = [] self._carbon_event_handler_refs = [] for func_name in self._platform_event_names: if not hasattr(self, func_name): continue func = getattr(self, func_name) self._install_event_handler(func) def _install_event_handler(self, func): if self._fullscreen: target = carbon.GetApplicationEventTarget() else: target = carbon.GetWindowEventTarget(self._window) for event_class, event_kind in func._platform_event_data: # TODO: could just build up array of class/kind proc = EventHandlerProcPtr(func) self._carbon_event_handlers.append(proc) upp = carbon.NewEventHandlerUPP(proc) types = EventTypeSpec() types.eventClass = event_class types.eventKind = event_kind handler_ref = EventHandlerRef() carbon.InstallEventHandler( target, upp, 1, byref(types), c_void_p(), byref(handler_ref)) self._carbon_event_handler_refs.append(handler_ref) def _remove_event_handlers(self): for ref in self._carbon_event_handler_refs: carbon.RemoveEventHandler(ref) self._carbon_event_handler_refs = [] self._carbon_event_handlers = [] # Carbon event handlers @CarbonEventHandler(kEventClassTextInput, kEventTextInputUnicodeForKeyEvent) def _on_text_input(self, next_handler, ev, data): size = c_uint32() carbon.GetEventParameter(ev, kEventParamTextInputSendText, typeUTF8Text, c_void_p(), 0, byref(size), c_void_p()) text = create_string_buffer(size.value) carbon.GetEventParameter(ev, kEventParamTextInputSendText, typeUTF8Text, c_void_p(), size.value, c_void_p(), byref(text)) text = text.value.decode('utf8') raw_event = EventRef() carbon.GetEventParameter(ev, kEventParamTextInputSendKeyboardEvent, typeEventRef, c_void_p(), sizeof(raw_event), c_void_p(), byref(raw_event)) symbol, modifiers = self._get_symbol_and_modifiers(raw_event) motion_modifiers = modifiers & \ (key.MOD_COMMAND | key.MOD_CTRL | key.MOD_OPTION) if (symbol, motion_modifiers) in _motion_map: motion = _motion_map[symbol, motion_modifiers] if modifiers & key.MOD_SHIFT: self.dispatch_event('on_text_motion_select', motion) else: self.dispatch_event('on_text_motion', motion) elif ((unicodedata.category(text[0]) != 'Cc' or text == u'\r') and not (modifiers & key.MOD_COMMAND)): self.dispatch_event('on_text', text) return noErr @CarbonEventHandler(kEventClassKeyboard, kEventRawKeyUp) def _on_key_up(self, next_handler, ev, data): symbol, modifiers = self._get_symbol_and_modifiers(ev) if symbol: self.dispatch_event('on_key_release', symbol, modifiers) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassKeyboard, kEventRawKeyDown) def _on_key_down(self, next_handler, ev, data): symbol, modifiers = self._get_symbol_and_modifiers(ev) if symbol: self.dispatch_event('on_key_press', symbol, modifiers) carbon.CallNextEventHandler(next_handler, ev) return noErr @staticmethod def _get_symbol_and_modifiers(ev): # The unicode char help processing virtual keycodes (see issue 405) wchar = c_wchar() carbon.GetEventParameter(ev, kEventParamKeyUnicodes, typeUnicodeText, c_void_p(), sizeof(wchar), c_void_p(), byref(wchar)) try: wchar = str((wchar.value)).upper() except UnicodeEncodeError: # (this fix for issue 405 caused a bug itself (see comments 6-7); # this try/except fixes it) wchar = None # If the unicode char is within charmap keys (ascii value), then we use # the corresponding symbol. if wchar in charmap.keys(): symbol = charmap[wchar] else: sym = c_uint32() carbon.GetEventParameter(ev, kEventParamKeyCode, typeUInt32, c_void_p(), sizeof(sym), c_void_p(), byref(sym)) symbol = keymap.get(sym.value, None) if symbol is None: symbol = key.user_key(sym.value) modifiers = c_uint32() carbon.GetEventParameter(ev, kEventParamKeyModifiers, typeUInt32, c_void_p(), sizeof(modifiers), c_void_p(), byref(modifiers)) return (symbol, CarbonWindow._map_modifiers(modifiers.value)) @staticmethod def _map_modifiers(modifiers): mapped_modifiers = 0 if modifiers & (shiftKey | rightShiftKey): mapped_modifiers |= key.MOD_SHIFT if modifiers & (controlKey | rightControlKey): mapped_modifiers |= key.MOD_CTRL if modifiers & (optionKey | rightOptionKey): mapped_modifiers |= key.MOD_OPTION if modifiers & alphaLock: mapped_modifiers |= key.MOD_CAPSLOCK if modifiers & cmdKey: mapped_modifiers |= key.MOD_COMMAND return mapped_modifiers @CarbonEventHandler(kEventClassKeyboard, kEventRawKeyModifiersChanged) def _on_modifiers_changed(self, next_handler, ev, data): modifiers = c_uint32() carbon.GetEventParameter(ev, kEventParamKeyModifiers, typeUInt32, c_void_p(), sizeof(modifiers), c_void_p(), byref(modifiers)) modifiers = modifiers.value deltas = modifiers ^ self._current_modifiers for mask, k in [ (controlKey, key.LCTRL), (shiftKey, key.LSHIFT), (cmdKey, key.LCOMMAND), (optionKey, key.LOPTION), (rightShiftKey, key.RSHIFT), (rightOptionKey, key.ROPTION), (rightControlKey, key.RCTRL), (alphaLock, key.CAPSLOCK), (numLock, key.NUMLOCK)]: if deltas & mask: if modifiers & mask: self.dispatch_event('on_key_press', k, self._mapped_modifiers) else: self.dispatch_event('on_key_release', k, self._mapped_modifiers) carbon.CallNextEventHandler(next_handler, ev) self._mapped_modifiers = self._map_modifiers(modifiers) self._current_modifiers = modifiers return noErr def _get_mouse_position(self, ev): position = HIPoint() carbon.GetEventParameter(ev, kEventParamMouseLocation, typeHIPoint, c_void_p(), sizeof(position), c_void_p(), byref(position)) bounds = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(bounds)) return (int(position.x - bounds.left - self._view_x), int(position.y - bounds.top - self._view_y)) def _get_mouse_buttons_changed(self): button_state = self._get_mouse_buttons() change = self._mouse_button_state ^ button_state self._mouse_button_state = button_state return change @staticmethod def _get_mouse_buttons(): buttons = carbon.GetCurrentEventButtonState() button_state = 0 if buttons & 0x1: button_state |= mouse.LEFT if buttons & 0x2: button_state |= mouse.RIGHT if buttons & 0x4: button_state |= mouse.MIDDLE return button_state @staticmethod def _get_modifiers(ev): modifiers = c_uint32() carbon.GetEventParameter(ev, kEventParamKeyModifiers, typeUInt32, c_void_p(), sizeof(modifiers), c_void_p(), byref(modifiers)) return CarbonWindow._map_modifiers(modifiers.value) def _get_mouse_in_content(self, ev, x, y): if self._fullscreen: return 0 <= x < self._width and 0 <= y < self._height else: position = Point() carbon.GetEventParameter(ev, kEventParamMouseLocation, typeQDPoint, c_void_p(), sizeof(position), c_void_p(), byref(position)) return carbon.FindWindow(position, None) == inContent @CarbonEventHandler(kEventClassMouse, kEventMouseDown) def _on_mouse_down(self, next_handler, ev, data): x, y = self._get_mouse_position(ev) if self._get_mouse_in_content(ev, x, y): button = self._get_mouse_buttons_changed() modifiers = self._get_modifiers(ev) if button is not None: y = self.height - y self.dispatch_event('on_mouse_press', x, y, button, modifiers) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassMouse, kEventMouseUp) def _on_mouse_up(self, next_handler, ev, data): # Always report mouse up, even out of content area, because it's # probably after a drag gesture. button = self._get_mouse_buttons_changed() modifiers = self._get_modifiers(ev) if button is not None: x, y = self._get_mouse_position(ev) y = self.height - y self.dispatch_event('on_mouse_release', x, y, button, modifiers) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassMouse, kEventMouseMoved) def _on_mouse_moved(self, next_handler, ev, data): x, y = self._get_mouse_position(ev) if (self._get_mouse_in_content(ev, x, y) and not self._mouse_ignore_motion): y = self.height - y self._mouse_x = x self._mouse_y = y delta = HIPoint() carbon.GetEventParameter(ev, kEventParamMouseDelta, typeHIPoint, c_void_p(), sizeof(delta), c_void_p(), byref(delta)) # Motion event self.dispatch_event('on_mouse_motion', x, y, delta.x, -delta.y) elif self._mouse_ignore_motion: self._mouse_ignore_motion = False carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassMouse, kEventMouseDragged) def _on_mouse_dragged(self, next_handler, ev, data): button = self._get_mouse_buttons() modifiers = self._get_modifiers(ev) if button is not None: x, y = self._get_mouse_position(ev) y = self.height - y self._mouse_x = x self._mouse_y = y delta = HIPoint() carbon.GetEventParameter(ev, kEventParamMouseDelta, typeHIPoint, c_void_p(), sizeof(delta), c_void_p(), byref(delta)) # Drag event self.dispatch_event('on_mouse_drag', x, y, delta.x, -delta.y, button, modifiers) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassMouse, kEventMouseEntered) def _on_mouse_entered(self, next_handler, ev, data): x, y = self._get_mouse_position(ev) y = self.height - y self._mouse_x = x self._mouse_y = y self._mouse_in_window = True self.set_mouse_platform_visible() self.dispatch_event('on_mouse_enter', x, y) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassMouse, kEventMouseExited) def _on_mouse_exited(self, next_handler, ev, data): x, y = self._get_mouse_position(ev) y = self.height - y self._mouse_in_window = False self.set_mouse_platform_visible() self.dispatch_event('on_mouse_leave', x, y) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassMouse, kEventMouseWheelMoved) def _on_mouse_wheel_moved(self, next_handler, ev, data): x, y = self._get_mouse_position(ev) y = self.height - y axis = EventMouseWheelAxis() carbon.GetEventParameter(ev, kEventParamMouseWheelAxis, typeMouseWheelAxis, c_void_p(), sizeof(axis), c_void_p(), byref(axis)) delta = c_long() carbon.GetEventParameter(ev, kEventParamMouseWheelDelta, typeSInt32, c_void_p(), sizeof(delta), c_void_p(), byref(delta)) if axis.value == kEventMouseWheelAxisX: self.dispatch_event('on_mouse_scroll', x, y, delta.value, 0) else: self.dispatch_event('on_mouse_scroll', x, y, 0, delta.value) # _Don't_ call the next handler, which is application, as this then # calls our window handler again. #carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowClose) def _on_window_close(self, next_handler, ev, data): self.dispatch_event('on_close') # Presumably the next event handler is the one that closes # the window; don't do that here. #carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowResizeStarted) def _on_window_resize_started(self, next_handler, ev, data): from pyglet import app if app.event_loop is not None: app.event_loop.enter_blocking() carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowResizeCompleted) def _on_window_resize_completed(self, next_handler, ev, data): from pyglet import app if app.event_loop is not None: app.event_loop.exit_blocking() rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) width = rect.right - rect.left height = rect.bottom - rect.top self.switch_to() self.dispatch_event('on_resize', width, height) self.dispatch_event('on_expose') carbon.CallNextEventHandler(next_handler, ev) return noErr _dragging = False @CarbonEventHandler(kEventClassWindow, kEventWindowDragStarted) def _on_window_drag_started(self, next_handler, ev, data): self._dragging = True from pyglet import app if app.event_loop is not None: app.event_loop.enter_blocking() carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowDragCompleted) def _on_window_drag_completed(self, next_handler, ev, data): self._dragging = False from pyglet import app if app.event_loop is not None: app.event_loop.exit_blocking() rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) self.dispatch_event('on_move', rect.left, rect.top) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowBoundsChanging) def _on_window_bounds_changing(self, next_handler, ev, data): carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowBoundsChanged) def _on_window_bounds_change(self, next_handler, ev, data): self._update_track_region() rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) width = rect.right - rect.left height = rect.bottom - rect.top if width != self._width or height != self._height: self._update_drawable() self.switch_to() self.dispatch_event('on_resize', width, height) from pyglet import app if app.event_loop is not None: app.event_loop.enter_blocking() self._width = width self._height = height else: self.dispatch_event('on_move', rect.left, rect.top) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowZoomed) def _on_window_zoomed(self, next_handler, ev, data): rect = Rect() carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect)) width = rect.right - rect.left height = rect.bottom - rect.top self.dispatch_event('on_move', rect.left, rect.top) self.dispatch_event('on_resize', width, height) carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowActivated) def _on_window_activated(self, next_handler, ev, data): self.dispatch_event('on_activate') carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowDeactivated) def _on_window_deactivated(self, next_handler, ev, data): self.dispatch_event('on_deactivate') carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowShown) @CarbonEventHandler(kEventClassWindow, kEventWindowExpanded) def _on_window_shown(self, next_handler, ev, data): self._update_drawable() # XXX not needed here according to apple docs self.dispatch_event('on_show') carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowHidden) @CarbonEventHandler(kEventClassWindow, kEventWindowCollapsed) def _on_window_hidden(self, next_handler, ev, data): self.dispatch_event('on_hide') carbon.CallNextEventHandler(next_handler, ev) return noErr @CarbonEventHandler(kEventClassWindow, kEventWindowDrawContent) def _on_window_draw_content(self, next_handler, ev, data): self.dispatch_event('on_expose') carbon.CallNextEventHandler(next_handler, ev) return noErr CarbonWindow.register_event_type('on_recreate_immediate')
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from ctypes import * import unicodedata import warnings from pyglet import compat_platform if compat_platform not in ('cygwin', 'win32'): raise ImportError('Not a win32 platform.') import pyglet from pyglet.window import BaseWindow, \ WindowException, MouseCursor, DefaultMouseCursor, _PlatformEventHandler, \ _ViewEventHandler from pyglet.event import EventDispatcher from pyglet.window import key from pyglet.window import mouse from pyglet.canvas.win32 import Win32Canvas from pyglet.libs.win32 import _user32, _kernel32, _gdi32 from pyglet.libs.win32.constants import * from pyglet.libs.win32.winkey import * from pyglet.libs.win32.types import * # symbol,ctrl -> motion mapping _motion_map = { (key.UP, False): key.MOTION_UP, (key.RIGHT, False): key.MOTION_RIGHT, (key.DOWN, False): key.MOTION_DOWN, (key.LEFT, False): key.MOTION_LEFT, (key.RIGHT, True): key.MOTION_NEXT_WORD, (key.LEFT, True): key.MOTION_PREVIOUS_WORD, (key.HOME, False): key.MOTION_BEGINNING_OF_LINE, (key.END, False): key.MOTION_END_OF_LINE, (key.PAGEUP, False): key.MOTION_PREVIOUS_PAGE, (key.PAGEDOWN, False): key.MOTION_NEXT_PAGE, (key.HOME, True): key.MOTION_BEGINNING_OF_FILE, (key.END, True): key.MOTION_END_OF_FILE, (key.BACKSPACE, False): key.MOTION_BACKSPACE, (key.DELETE, False): key.MOTION_DELETE, } class Win32MouseCursor(MouseCursor): drawable = False def __init__(self, cursor): self.cursor = cursor # This is global state, we have to be careful not to set the same state twice, # which will throw off the ShowCursor counter. _win32_cursor_visible = True Win32EventHandler = _PlatformEventHandler ViewEventHandler = _ViewEventHandler class Win32Window(BaseWindow): _window_class = None _hwnd = None _dc = None _wgl_context = None _tracking = False _hidden = False _has_focus = False _exclusive_keyboard = False _exclusive_keyboard_focus = True _exclusive_mouse = False _exclusive_mouse_focus = True _exclusive_mouse_screen = None _exclusive_mouse_client = None _mouse_platform_visible = True _ws_style = 0 _ex_ws_style = 0 _minimum_size = None _maximum_size = None def __init__(self, *args, **kwargs): # Bind event handlers self._event_handlers = {} self._view_event_handlers = {} for func_name in self._platform_event_names: if not hasattr(self, func_name): continue func = getattr(self, func_name) for message in func._platform_event_data: if hasattr(func, '_view'): self._view_event_handlers[message] = func else: self._event_handlers[message] = func super(Win32Window, self).__init__(*args, **kwargs) def _recreate(self, changes): if 'context' in changes: self._wgl_context = None self._create() def _create(self): # Ensure style is set before determining width/height. if self._fullscreen: self._ws_style = WS_POPUP self._ex_ws_style = 0 # WS_EX_TOPMOST else: styles = { self.WINDOW_STYLE_DEFAULT: (WS_OVERLAPPEDWINDOW, 0), self.WINDOW_STYLE_DIALOG: (WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU, WS_EX_DLGMODALFRAME), self.WINDOW_STYLE_TOOL: (WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU, WS_EX_TOOLWINDOW), self.WINDOW_STYLE_BORDERLESS: (WS_POPUP, 0), } self._ws_style, self._ex_ws_style = styles[self._style] if self._resizable and not self._fullscreen: self._ws_style |= WS_THICKFRAME else: self._ws_style &= ~(WS_THICKFRAME|WS_MAXIMIZEBOX) if self._fullscreen: width = self.screen.width height = self.screen.height else: width, height = \ self._client_to_window_size(self._width, self._height) if not self._window_class: module = _kernel32.GetModuleHandleW(None) white = _gdi32.GetStockObject(WHITE_BRUSH) black = _gdi32.GetStockObject(BLACK_BRUSH) self._window_class = WNDCLASS() self._window_class.lpszClassName = u'GenericAppClass%d' % id(self) self._window_class.lpfnWndProc = WNDPROC(self._wnd_proc) self._window_class.style = CS_VREDRAW | CS_HREDRAW self._window_class.hInstance = 0 self._window_class.hIcon = _user32.LoadIconW(module, MAKEINTRESOURCE(1)) self._window_class.hbrBackground = black self._window_class.lpszMenuName = None self._window_class.cbClsExtra = 0 self._window_class.cbWndExtra = 0 _user32.RegisterClassW(byref(self._window_class)) self._view_window_class = WNDCLASS() self._view_window_class.lpszClassName = \ u'GenericViewClass%d' % id(self) self._view_window_class.lpfnWndProc = WNDPROC(self._wnd_proc_view) self._view_window_class.style = 0 self._view_window_class.hInstance = 0 self._view_window_class.hIcon = 0 self._view_window_class.hbrBackground = white self._view_window_class.lpszMenuName = None self._view_window_class.cbClsExtra = 0 self._view_window_class.cbWndExtra = 0 _user32.RegisterClassW(byref(self._view_window_class)) if not self._hwnd: self._hwnd = _user32.CreateWindowExW( self._ex_ws_style, self._window_class.lpszClassName, u'', self._ws_style, CW_USEDEFAULT, CW_USEDEFAULT, width, height, 0, 0, self._window_class.hInstance, 0) self._view_hwnd = _user32.CreateWindowExW( 0, self._view_window_class.lpszClassName, u'', WS_CHILD | WS_VISIBLE, 0, 0, 0, 0, self._hwnd, 0, self._view_window_class.hInstance, 0) self._dc = _user32.GetDC(self._view_hwnd) else: # Window already exists, update it with new style # We need to hide window here, otherwise Windows forgets # to redraw the whole screen after leaving fullscreen. _user32.ShowWindow(self._hwnd, SW_HIDE) _user32.SetWindowLongW(self._hwnd, GWL_STYLE, self._ws_style) _user32.SetWindowLongW(self._hwnd, GWL_EXSTYLE, self._ex_ws_style) if self._fullscreen: hwnd_after = HWND_TOPMOST else: hwnd_after = HWND_NOTOPMOST # Position and size window if self._fullscreen: _user32.SetWindowPos(self._hwnd, hwnd_after, self._screen.x, self._screen.y, width, height, SWP_FRAMECHANGED) elif False: # TODO location not in pyglet API x, y = self._client_to_window_pos(*factory.get_location()) _user32.SetWindowPos(self._hwnd, hwnd_after, x, y, width, height, SWP_FRAMECHANGED) else: _user32.SetWindowPos(self._hwnd, hwnd_after, 0, 0, width, height, SWP_NOMOVE | SWP_FRAMECHANGED) self._update_view_location(self._width, self._height) # Context must be created after window is created. if not self._wgl_context: self.canvas = Win32Canvas(self.display, self._view_hwnd, self._dc) self.context.attach(self.canvas) self._wgl_context = self.context._context self.set_caption(self._caption) self.switch_to() self.set_vsync(self._vsync) if self._visible: self.set_visible() self.dispatch_event('on_expose') # Might need resize event if going from fullscreen to fullscreen self.dispatch_event('on_resize', self._width, self._height) def _update_view_location(self, width, height): if self._fullscreen: x = (self.screen.width - width) // 2 y = (self.screen.height - height) // 2 else: x = y = 0 _user32.SetWindowPos(self._view_hwnd, 0, x, y, width, height, SWP_NOZORDER | SWP_NOOWNERZORDER) def close(self): super(Win32Window, self).close() if not self._hwnd: return _user32.DestroyWindow(self._hwnd) _user32.UnregisterClassW(self._window_class.lpszClassName, 0) self.set_mouse_platform_visible(True) self._hwnd = None self._dc = None self._wgl_context = None def _get_vsync(self): return self.context.get_vsync() vsync = property(_get_vsync) # overrides BaseWindow property def set_vsync(self, vsync): if pyglet.options['vsync'] is not None: vsync = pyglet.options['vsync'] self.context.set_vsync(vsync) def switch_to(self): self.context.set_current() def flip(self): self.draw_mouse_cursor() self.context.flip() def set_location(self, x, y): x, y = self._client_to_window_pos(x, y) _user32.SetWindowPos(self._hwnd, 0, x, y, 0, 0, (SWP_NOZORDER | SWP_NOSIZE | SWP_NOOWNERZORDER)) def get_location(self): rect = RECT() _user32.GetClientRect(self._hwnd, byref(rect)) point = POINT() point.x = rect.left point.y = rect.top _user32.ClientToScreen(self._hwnd, byref(point)) return point.x, point.y def set_size(self, width, height): if self._fullscreen: raise WindowException('Cannot set size of fullscreen window.') width, height = self._client_to_window_size(width, height) _user32.SetWindowPos(self._hwnd, 0, 0, 0, width, height, (SWP_NOZORDER | SWP_NOMOVE | SWP_NOOWNERZORDER)) def get_size(self): #rect = RECT() #_user32.GetClientRect(self._hwnd, byref(rect)) #return rect.right - rect.left, rect.bottom - rect.top return self._width, self._height def set_minimum_size(self, width, height): self._minimum_size = width, height def set_maximum_size(self, width, height): self._maximum_size = width, height def activate(self): _user32.SetForegroundWindow(self._hwnd) def set_visible(self, visible=True): if visible: insertAfter = HWND_TOPMOST if self._fullscreen else HWND_TOP _user32.SetWindowPos(self._hwnd, insertAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW) self.dispatch_event('on_show') self.activate() self.dispatch_event('on_resize', self._width, self._height) else: _user32.ShowWindow(self._hwnd, SW_HIDE) self.dispatch_event('on_hide') self._visible = visible self.set_mouse_platform_visible() def minimize(self): _user32.ShowWindow(self._hwnd, SW_MINIMIZE) def maximize(self): _user32.ShowWindow(self._hwnd, SW_MAXIMIZE) def set_caption(self, caption): self._caption = caption _user32.SetWindowTextW(self._hwnd, c_wchar_p(caption)) def set_mouse_platform_visible(self, platform_visible=None): if platform_visible is None: platform_visible = (self._mouse_visible and not self._exclusive_mouse and not self._mouse_cursor.drawable) or \ (not self._mouse_in_window or not self._has_focus) if platform_visible and not self._mouse_cursor.drawable: if isinstance(self._mouse_cursor, Win32MouseCursor): cursor = self._mouse_cursor.cursor else: cursor = _user32.LoadCursorW(None, MAKEINTRESOURCE(IDC_ARROW)) _user32.SetClassLongW(self._view_hwnd, GCL_HCURSOR, cursor) _user32.SetCursor(cursor) if platform_visible == self._mouse_platform_visible: return # Avoid calling ShowCursor with the current visibility (which would # push the counter too far away from zero). global _win32_cursor_visible if _win32_cursor_visible != platform_visible: _user32.ShowCursor(platform_visible) _win32_cursor_visible = platform_visible self._mouse_platform_visible = platform_visible def _reset_exclusive_mouse_screen(self): '''Recalculate screen coords of mouse warp point for exclusive mouse.''' p = POINT() rect = RECT() _user32.GetClientRect(self._view_hwnd, byref(rect)) _user32.MapWindowPoints(self._view_hwnd, HWND_DESKTOP, byref(rect), 2) p.x = (rect.left + rect.right) // 2 p.y = (rect.top + rect.bottom) // 2 # This is the point the mouse will be kept at while in exclusive # mode. self._exclusive_mouse_screen = p.x, p.y self._exclusive_mouse_client = p.x - rect.left, p.y - rect.top def set_exclusive_mouse(self, exclusive=True): if self._exclusive_mouse == exclusive and \ self._exclusive_mouse_focus == self._has_focus: return if exclusive and self._has_focus: # Move mouse to the center of the window. self._reset_exclusive_mouse_screen() x, y = self._exclusive_mouse_screen self.set_mouse_position(x, y, absolute=True) # Clip to client area, to prevent large mouse movements taking # it outside the client area. rect = RECT() _user32.GetClientRect(self._view_hwnd, byref(rect)) _user32.MapWindowPoints(self._view_hwnd, HWND_DESKTOP, byref(rect), 2) _user32.ClipCursor(byref(rect)) else: # Release clip _user32.ClipCursor(None) self._exclusive_mouse = exclusive self._exclusive_mouse_focus = self._has_focus self.set_mouse_platform_visible() def set_mouse_position(self, x, y, absolute=False): if not absolute: rect = RECT() _user32.GetClientRect(self._view_hwnd, byref(rect)) _user32.MapWindowPoints(self._view_hwnd, HWND_DESKTOP, byref(rect), 2) x = x + rect.left y = rect.top + (rect.bottom - rect.top) - y _user32.SetCursorPos(x, y) def set_exclusive_keyboard(self, exclusive=True): if self._exclusive_keyboard == exclusive and \ self._exclusive_keyboard_focus == self._has_focus: return if exclusive and self._has_focus: _user32.RegisterHotKey(self._hwnd, 0, WIN32_MOD_ALT, VK_TAB) else: _user32.UnregisterHotKey(self._hwnd, 0) self._exclusive_keyboard = exclusive self._exclusive_keyboard_focus = self._has_focus def get_system_mouse_cursor(self, name): if name == self.CURSOR_DEFAULT: return DefaultMouseCursor() names = { self.CURSOR_CROSSHAIR: IDC_CROSS, self.CURSOR_HAND: IDC_HAND, self.CURSOR_HELP: IDC_HELP, self.CURSOR_NO: IDC_NO, self.CURSOR_SIZE: IDC_SIZEALL, self.CURSOR_SIZE_UP: IDC_SIZENS, self.CURSOR_SIZE_UP_RIGHT: IDC_SIZENESW, self.CURSOR_SIZE_RIGHT: IDC_SIZEWE, self.CURSOR_SIZE_DOWN_RIGHT: IDC_SIZENWSE, self.CURSOR_SIZE_DOWN: IDC_SIZENS, self.CURSOR_SIZE_DOWN_LEFT: IDC_SIZENESW, self.CURSOR_SIZE_LEFT: IDC_SIZEWE, self.CURSOR_SIZE_UP_LEFT: IDC_SIZENWSE, self.CURSOR_SIZE_UP_DOWN: IDC_SIZENS, self.CURSOR_SIZE_LEFT_RIGHT: IDC_SIZEWE, self.CURSOR_TEXT: IDC_IBEAM, self.CURSOR_WAIT: IDC_WAIT, self.CURSOR_WAIT_ARROW: IDC_APPSTARTING, } if name not in names: raise RuntimeError('Unknown cursor name "%s"' % name) cursor = _user32.LoadCursorW(None, MAKEINTRESOURCE(names[name])) return Win32MouseCursor(cursor) def set_icon(self, *images): # XXX Undocumented AFAICT, but XP seems happy to resize an image # of any size, so no scaling necessary. def best_image(width, height): # A heuristic for finding closest sized image to required size. image = images[0] for img in images: if img.width == width and img.height == height: # Exact match always used return img elif img.width >= width and \ img.width * img.height > image.width * image.height: # At least wide enough, and largest area image = img return image def get_icon(image): # Alpha-blended icon: see http://support.microsoft.com/kb/318876 format = 'BGRA' pitch = len(format) * image.width header = BITMAPV5HEADER() header.bV5Size = sizeof(header) header.bV5Width = image.width header.bV5Height = image.height header.bV5Planes = 1 header.bV5BitCount = 32 header.bV5Compression = BI_BITFIELDS header.bV5RedMask = 0x00ff0000 header.bV5GreenMask = 0x0000ff00 header.bV5BlueMask = 0x000000ff header.bV5AlphaMask = 0xff000000 hdc = _user32.GetDC(None) dataptr = c_void_p() bitmap = _gdi32.CreateDIBSection(hdc, byref(header), DIB_RGB_COLORS, byref(dataptr), None, 0) _user32.ReleaseDC(None, hdc) data = image.get_data(format, pitch) memmove(dataptr, data, len(data)) mask = _gdi32.CreateBitmap(image.width, image.height, 1, 1, None) iconinfo = ICONINFO() iconinfo.fIcon = True iconinfo.hbmMask = mask iconinfo.hbmColor = bitmap icon = _user32.CreateIconIndirect(byref(iconinfo)) _gdi32.DeleteObject(mask) _gdi32.DeleteObject(bitmap) return icon # Set large icon image = best_image(_user32.GetSystemMetrics(SM_CXICON), _user32.GetSystemMetrics(SM_CYICON)) icon = get_icon(image) _user32.SetClassLongW(self._hwnd, GCL_HICON, icon) # Set small icon image = best_image(_user32.GetSystemMetrics(SM_CXSMICON), _user32.GetSystemMetrics(SM_CYSMICON)) icon = get_icon(image) _user32.SetClassLongW(self._hwnd, GCL_HICONSM, icon) # Private util def _client_to_window_size(self, width, height): rect = RECT() rect.left = 0 rect.top = 0 rect.right = width rect.bottom = height _user32.AdjustWindowRectEx(byref(rect), self._ws_style, False, self._ex_ws_style) return rect.right - rect.left, rect.bottom - rect.top def _client_to_window_pos(self, x, y): rect = RECT() rect.left = x rect.top = y _user32.AdjustWindowRectEx(byref(rect), self._ws_style, False, self._ex_ws_style) return rect.left, rect.top # Event dispatching def dispatch_events(self): from pyglet import app app.platform_event_loop.start() self._allow_dispatch_event = True self.dispatch_pending_events() msg = MSG() while _user32.PeekMessageW(byref(msg), 0, 0, 0, PM_REMOVE): _user32.TranslateMessage(byref(msg)) _user32.DispatchMessageW(byref(msg)) self._allow_dispatch_event = False def dispatch_pending_events(self): while self._event_queue: event = self._event_queue.pop(0) if type(event[0]) is str: # pyglet event EventDispatcher.dispatch_event(self, *event) else: # win32 event event[0](*event[1:]) def _wnd_proc(self, hwnd, msg, wParam, lParam): event_handler = self._event_handlers.get(msg, None) result = 0 if event_handler: if self._allow_dispatch_event or not self._enable_event_queue: result = event_handler(msg, wParam, lParam) else: self._event_queue.append((event_handler, msg, wParam, lParam)) result = 0 if not result and msg != WM_CLOSE: result = _user32.DefWindowProcW(hwnd, msg, wParam, lParam) return result def _wnd_proc_view(self, hwnd, msg, wParam, lParam): event_handler = self._view_event_handlers.get(msg, None) result = 0 if event_handler: if self._allow_dispatch_event or not self._enable_event_queue: result = event_handler(msg, wParam, lParam) else: self._event_queue.append((event_handler, msg, wParam, lParam)) result = 0 if not result and msg != WM_CLOSE: result = _user32.DefWindowProcW(hwnd, msg, wParam, lParam) return result # Event handlers def _get_modifiers(self, key_lParam=0): modifiers = 0 if _user32.GetKeyState(VK_SHIFT) & 0xff00: modifiers |= key.MOD_SHIFT if _user32.GetKeyState(VK_CONTROL) & 0xff00: modifiers |= key.MOD_CTRL if _user32.GetKeyState(VK_LWIN) & 0xff00: modifiers |= key.MOD_WINDOWS if _user32.GetKeyState(VK_CAPITAL) & 0x00ff: # toggle modifiers |= key.MOD_CAPSLOCK if _user32.GetKeyState(VK_NUMLOCK) & 0x00ff: # toggle modifiers |= key.MOD_NUMLOCK if _user32.GetKeyState(VK_SCROLL) & 0x00ff: # toggle modifiers |= key.MOD_SCROLLLOCK if key_lParam: if key_lParam & (1 << 29): modifiers |= key.MOD_ALT elif _user32.GetKeyState(VK_MENU) < 0: modifiers |= key.MOD_ALT return modifiers @staticmethod def _get_location(lParam): x = c_int16(lParam & 0xffff).value y = c_int16(lParam >> 16).value return x, y @Win32EventHandler(WM_KEYDOWN) @Win32EventHandler(WM_KEYUP) @Win32EventHandler(WM_SYSKEYDOWN) @Win32EventHandler(WM_SYSKEYUP) def _event_key(self, msg, wParam, lParam): repeat = False if lParam & (1 << 30): if msg not in (WM_KEYUP, WM_SYSKEYUP): repeat = True ev = 'on_key_release' else: ev = 'on_key_press' symbol = keymap.get(wParam, None) if symbol is None: ch = _user32.MapVirtualKeyW(wParam, MAPVK_VK_TO_CHAR) symbol = chmap.get(ch) if symbol is None: symbol = key.user_key(wParam) elif symbol == key.LCTRL and lParam & (1 << 24): symbol = key.RCTRL elif symbol == key.LALT and lParam & (1 << 24): symbol = key.RALT elif symbol == key.LSHIFT: pass # TODO: some magic with getstate to find out if it's the # right or left shift key. modifiers = self._get_modifiers(lParam) if not repeat: self.dispatch_event(ev, symbol, modifiers) ctrl = modifiers & key.MOD_CTRL != 0 if (symbol, ctrl) in _motion_map and msg not in (WM_KEYUP, WM_SYSKEYUP): motion = _motion_map[symbol, ctrl] if modifiers & key.MOD_SHIFT: self.dispatch_event('on_text_motion_select', motion) else: self.dispatch_event('on_text_motion', motion) # Send on to DefWindowProc if not exclusive. if self._exclusive_keyboard: return 0 else: return None @Win32EventHandler(WM_CHAR) def _event_char(self, msg, wParam, lParam): text = unichr(wParam) if unicodedata.category(text) != 'Cc' or text == '\r': self.dispatch_event('on_text', text) return 0 @ViewEventHandler @Win32EventHandler(WM_MOUSEMOVE) def _event_mousemove(self, msg, wParam, lParam): x, y = self._get_location(lParam) if (x, y) == self._exclusive_mouse_client: # Ignore the event caused by SetCursorPos self._mouse_x = x self._mouse_y = y return 0 y = self._height - y if self._exclusive_mouse and self._has_focus: # Reset mouse position (so we don't hit the edge of the screen). _x, _y = self._exclusive_mouse_screen self.set_mouse_position(_x, _y, absolute=True) dx = x - self._mouse_x dy = y - self._mouse_y if not self._tracking: # There is no WM_MOUSEENTER message (!), so fake it from the # first WM_MOUSEMOVE event after leaving. Use self._tracking # to determine when to recreate the tracking structure after # re-entering (to track the next WM_MOUSELEAVE). self._mouse_in_window = True self.set_mouse_platform_visible() self.dispatch_event('on_mouse_enter', x, y) self._tracking = True track = TRACKMOUSEEVENT() track.cbSize = sizeof(track) track.dwFlags = TME_LEAVE track.hwndTrack = self._view_hwnd _user32.TrackMouseEvent(byref(track)) # Don't generate motion/drag events when mouse hasn't moved. (Issue # 305) if self._mouse_x == x and self._mouse_y == y: return 0 self._mouse_x = x self._mouse_y = y buttons = 0 if wParam & MK_LBUTTON: buttons |= mouse.LEFT if wParam & MK_MBUTTON: buttons |= mouse.MIDDLE if wParam & MK_RBUTTON: buttons |= mouse.RIGHT if buttons: # Drag event modifiers = self._get_modifiers() self.dispatch_event('on_mouse_drag', x, y, dx, dy, buttons, modifiers) else: # Motion event self.dispatch_event('on_mouse_motion', x, y, dx, dy) return 0 @ViewEventHandler @Win32EventHandler(WM_MOUSELEAVE) def _event_mouseleave(self, msg, wParam, lParam): point = POINT() _user32.GetCursorPos(byref(point)) _user32.ScreenToClient(self._view_hwnd, byref(point)) x = point.x y = self._height - point.y self._tracking = False self._mouse_in_window = False self.set_mouse_platform_visible() self.dispatch_event('on_mouse_leave', x, y) return 0 def _event_mousebutton(self, ev, button, lParam): if ev == 'on_mouse_press': _user32.SetCapture(self._view_hwnd) else: _user32.ReleaseCapture() x, y = self._get_location(lParam) y = self._height - y self.dispatch_event(ev, x, y, button, self._get_modifiers()) return 0 @ViewEventHandler @Win32EventHandler(WM_LBUTTONDOWN) def _event_lbuttondown(self, msg, wParam, lParam): return self._event_mousebutton( 'on_mouse_press', mouse.LEFT, lParam) @ViewEventHandler @Win32EventHandler(WM_LBUTTONUP) def _event_lbuttonup(self, msg, wParam, lParam): return self._event_mousebutton( 'on_mouse_release', mouse.LEFT, lParam) @ViewEventHandler @Win32EventHandler(WM_MBUTTONDOWN) def _event_mbuttondown(self, msg, wParam, lParam): return self._event_mousebutton( 'on_mouse_press', mouse.MIDDLE, lParam) @ViewEventHandler @Win32EventHandler(WM_MBUTTONUP) def _event_mbuttonup(self, msg, wParam, lParam): return self._event_mousebutton( 'on_mouse_release', mouse.MIDDLE, lParam) @ViewEventHandler @Win32EventHandler(WM_RBUTTONDOWN) def _event_rbuttondown(self, msg, wParam, lParam): return self._event_mousebutton( 'on_mouse_press', mouse.RIGHT, lParam) @ViewEventHandler @Win32EventHandler(WM_RBUTTONUP) def _event_rbuttonup(self, msg, wParam, lParam): return self._event_mousebutton( 'on_mouse_release', mouse.RIGHT, lParam) @Win32EventHandler(WM_MOUSEWHEEL) def _event_mousewheel(self, msg, wParam, lParam): delta = c_short(wParam >> 16).value self.dispatch_event('on_mouse_scroll', self._mouse_x, self._mouse_y, 0, delta / float(WHEEL_DELTA)) return 0 @Win32EventHandler(WM_CLOSE) def _event_close(self, msg, wParam, lParam): self.dispatch_event('on_close') return 0 @ViewEventHandler @Win32EventHandler(WM_PAINT) def _event_paint(self, msg, wParam, lParam): self.dispatch_event('on_expose') # Validating the window using ValidateRect or ValidateRgn # doesn't clear the paint message when more than one window # is open [why?]; defer to DefWindowProc instead. return None @Win32EventHandler(WM_SIZING) def _event_sizing(self, msg, wParam, lParam): #rect = cast(lParam, POINTER(RECT)).contents #width, height = self.get_size() from pyglet import app if app.event_loop is not None: app.event_loop.enter_blocking() return 1 @Win32EventHandler(WM_SIZE) def _event_size(self, msg, wParam, lParam): if not self._dc: # Ignore window creation size event (appears for fullscreen # only) -- we haven't got DC or HWND yet. return None if wParam == SIZE_MINIMIZED: # Minimized, not resized. self._hidden = True self.dispatch_event('on_hide') return 0 if self._hidden: # Restored self._hidden = False self.dispatch_event('on_show') w, h = self._get_location(lParam) if not self._fullscreen: self._width, self._height = w, h self._update_view_location(self._width, self._height) self._reset_exclusive_mouse_screen() self.switch_to() self.dispatch_event('on_resize', self._width, self._height) return 0 @Win32EventHandler(WM_SYSCOMMAND) def _event_syscommand(self, msg, wParam, lParam): if wParam & 0xfff0 in (SC_MOVE, SC_SIZE): # Should be in WM_ENTERSIZEMOVE, but we never get that message. from pyglet import app if app.event_loop is not None: app.event_loop.enter_blocking() return 0 @Win32EventHandler(WM_MOVE) def _event_move(self, msg, wParam, lParam): x, y = self._get_location(lParam) self._reset_exclusive_mouse_screen() self.dispatch_event('on_move', x, y) return 0 @Win32EventHandler(WM_EXITSIZEMOVE) def _event_entersizemove(self, msg, wParam, lParam): from pyglet import app if app.event_loop is not None: app.event_loop.exit_blocking() return 0 ''' # Alternative to using WM_SETFOCUS and WM_KILLFOCUS. Which # is better? @Win32EventHandler(WM_ACTIVATE) def _event_activate(self, msg, wParam, lParam): if wParam & 0xffff == WA_INACTIVE: self.dispatch_event('on_deactivate') else: self.dispatch_event('on_activate') _user32.SetFocus(self._hwnd) return 0 ''' @Win32EventHandler(WM_SETFOCUS) def _event_setfocus(self, msg, wParam, lParam): self.dispatch_event('on_activate') self._has_focus = True self.set_exclusive_keyboard(self._exclusive_keyboard) self.set_exclusive_mouse(self._exclusive_mouse) return 0 @Win32EventHandler(WM_KILLFOCUS) def _event_killfocus(self, msg, wParam, lParam): self.dispatch_event('on_deactivate') self._has_focus = False self.set_exclusive_keyboard(self._exclusive_keyboard) self.set_exclusive_mouse(self._exclusive_mouse) return 0 @Win32EventHandler(WM_GETMINMAXINFO) def _event_getminmaxinfo(self, msg, wParam, lParam): info = MINMAXINFO.from_address(lParam) if self._minimum_size: info.ptMinTrackSize.x, info.ptMinTrackSize.y = \ self._client_to_window_size(*self._minimum_size) if self._maximum_size: info.ptMaxTrackSize.x, info.ptMaxTrackSize.y = \ self._client_to_window_size(*self._maximum_size) return 0 @Win32EventHandler(WM_ERASEBKGND) def _event_erasebkgnd(self, msg, wParam, lParam): # Prevent flicker during resize; but erase bkgnd if we're fullscreen. if self._fullscreen: return 0 else: return 1 @ViewEventHandler @Win32EventHandler(WM_ERASEBKGND) def _event_erasebkgnd_view(self, msg, wParam, lParam): # Prevent flicker during resize. return 1
Python
from pyglet.window import key, mouse from pyglet.libs.darwin.quartzkey import keymap, charmap from pyglet.libs.darwin.cocoapy import * NSTrackingArea = ObjCClass('NSTrackingArea') # Event data helper functions. def getMouseDelta(nsevent): dx = nsevent.deltaX() dy = -nsevent.deltaY() return int(round(dx)), int(round(dy)) def getMousePosition(self, nsevent): in_window = nsevent.locationInWindow() in_window = self.convertPoint_fromView_(in_window, None) x = int(in_window.x) y = int(in_window.y) # Must record mouse position for BaseWindow.draw_mouse_cursor to work. self._window._mouse_x = x self._window._mouse_y = y return x, y def getModifiers(nsevent): modifiers = 0 modifierFlags = nsevent.modifierFlags() if modifierFlags & NSAlphaShiftKeyMask: modifiers |= key.MOD_CAPSLOCK if modifierFlags & NSShiftKeyMask: modifiers |= key.MOD_SHIFT if modifierFlags & NSControlKeyMask: modifiers |= key.MOD_CTRL if modifierFlags & NSAlternateKeyMask: modifiers |= key.MOD_ALT modifiers |= key.MOD_OPTION if modifierFlags & NSCommandKeyMask: modifiers |= key.MOD_COMMAND if modifierFlags & NSFunctionKeyMask: modifiers |= key.MOD_FUNCTION return modifiers def getSymbol(nsevent): keycode = nsevent.keyCode() return keymap[keycode] class PygletView_Implementation(object): PygletView = ObjCSubclass('NSView', 'PygletView') @PygletView.method(b'@'+NSRectEncoding+PyObjectEncoding) def initWithFrame_cocoaWindow_(self, frame, window): # The tracking area is used to get mouseEntered, mouseExited, and cursorUpdate # events so that we can custom set the mouse cursor within the view. self._tracking_area = None self = ObjCInstance(send_super(self, 'initWithFrame:', frame, argtypes=[NSRect])) if not self: return None # CocoaWindow object. self._window = window self.updateTrackingAreas() # Create an instance of PygletTextView to handle text events. # We must do this because NSOpenGLView doesn't conform to the # NSTextInputClient protocol by default, and the insertText: method will # not do the right thing with respect to translating key sequences like # "Option-e", "e" if the protocol isn't implemented. So the easiest # thing to do is to subclass NSTextView which *does* implement the # protocol and let it handle text input. PygletTextView = ObjCClass('PygletTextView') self._textview = PygletTextView.alloc().initWithCocoaWindow_(window) # Add text view to the responder chain. self.addSubview_(self._textview) return self @PygletView.method('v') def dealloc(self): self._window = None #send_message(self.objc_self, 'removeFromSuperviewWithoutNeedingDisplay') self._textview.release() self._textview = None self._tracking_area.release() self._tracking_area = None send_super(self, 'dealloc') @PygletView.method('v') def updateTrackingAreas(self): # This method is called automatically whenever the tracking areas need to be # recreated, for example when window resizes. if self._tracking_area: self.removeTrackingArea_(self._tracking_area) self._tracking_area.release() self._tracking_area = None tracking_options = NSTrackingMouseEnteredAndExited | NSTrackingActiveInActiveApp | NSTrackingCursorUpdate frame = self.frame() self._tracking_area = NSTrackingArea.alloc().initWithRect_options_owner_userInfo_( frame, # rect tracking_options, # options self, # owner None) # userInfo self.addTrackingArea_(self._tracking_area) @PygletView.method('B') def canBecomeKeyView(self): return True @PygletView.method('B') def isOpaque(self): return True ## Event responders. # This method is called whenever the view changes size. @PygletView.method(b'v'+NSSizeEncoding) def setFrameSize_(self, size): send_super(self, 'setFrameSize:', size, argtypes=[NSSize]) # This method is called when view is first installed as the # contentView of window. Don't do anything on first call. # This also helps ensure correct window creation event ordering. if not self._window.context.canvas: return width, height = int(size.width), int(size.height) self._window.switch_to() self._window.context.update_geometry() self._window.dispatch_event("on_resize", width, height) self._window.dispatch_event("on_expose") # Can't get app.event_loop.enter_blocking() working with Cocoa, because # when mouse clicks on the window's resize control, Cocoa enters into a # mini-event loop that only responds to mouseDragged and mouseUp events. # This means that using NSTimer to call idle() won't work. Our kludge # is to override NSWindow's nextEventMatchingMask_etc method and call # idle() from there. if self.inLiveResize(): from pyglet import app if app.event_loop is not None: app.event_loop.idle() @PygletView.method('v@') def pygletKeyDown_(self, nsevent): symbol = getSymbol(nsevent) modifiers = getModifiers(nsevent) self._window.dispatch_event('on_key_press', symbol, modifiers) @PygletView.method('v@') def pygletKeyUp_(self, nsevent): symbol = getSymbol(nsevent) modifiers = getModifiers(nsevent) self._window.dispatch_event('on_key_release', symbol, modifiers) @PygletView.method('v@') def pygletFlagsChanged_(self, nsevent): # Handles on_key_press and on_key_release events for modifier keys. # Note that capslock is handled differently than other keys; it acts # as a toggle, so on_key_release is only sent when it's turned off. # TODO: Move these constants somewhere else. # Undocumented left/right modifier masks found by experimentation: NSLeftShiftKeyMask = 1 << 1 NSRightShiftKeyMask = 1 << 2 NSLeftControlKeyMask = 1 << 0 NSRightControlKeyMask = 1 << 13 NSLeftAlternateKeyMask = 1 << 5 NSRightAlternateKeyMask = 1 << 6 NSLeftCommandKeyMask = 1 << 3 NSRightCommandKeyMask = 1 << 4 maskForKey = { key.LSHIFT : NSLeftShiftKeyMask, key.RSHIFT : NSRightShiftKeyMask, key.LCTRL : NSLeftControlKeyMask, key.RCTRL : NSRightControlKeyMask, key.LOPTION : NSLeftAlternateKeyMask, key.ROPTION : NSRightAlternateKeyMask, key.LCOMMAND : NSLeftCommandKeyMask, key.RCOMMAND : NSRightCommandKeyMask, key.CAPSLOCK : NSAlphaShiftKeyMask, key.FUNCTION : NSFunctionKeyMask } symbol = getSymbol(nsevent) # Ignore this event if symbol is not a modifier key. We must check this # because e.g., we receive a flagsChanged message when using CMD-tab to # switch applications, with symbol == "a" when command key is released. if symbol not in maskForKey: return modifiers = getModifiers(nsevent) modifierFlags = nsevent.modifierFlags() if symbol and modifierFlags & maskForKey[symbol]: self._window.dispatch_event('on_key_press', symbol, modifiers) else: self._window.dispatch_event('on_key_release', symbol, modifiers) # Overriding this method helps prevent system beeps for unhandled events. @PygletView.method('B@') def performKeyEquivalent_(self, nsevent): # Let arrow keys and certain function keys pass through the responder # chain so that the textview can handle on_text_motion events. modifierFlags = nsevent.modifierFlags() if modifierFlags & NSNumericPadKeyMask: return False if modifierFlags & NSFunctionKeyMask: ch = cfstring_to_string(nsevent.charactersIgnoringModifiers()) if ch in (NSHomeFunctionKey, NSEndFunctionKey, NSPageUpFunctionKey, NSPageDownFunctionKey): return False # Send the key equivalent to the main menu to perform menu items. NSApp = ObjCClass('NSApplication').sharedApplication() NSApp.mainMenu().performKeyEquivalent_(nsevent) # Indicate that we've handled the event so system won't beep. return True @PygletView.method('v@') def mouseMoved_(self, nsevent): if self._window._mouse_ignore_motion: self._window._mouse_ignore_motion = False return # Don't send on_mouse_motion events if we're not inside the content rectangle. if not self._window._mouse_in_window: return x, y = getMousePosition(self, nsevent) dx, dy = getMouseDelta(nsevent) self._window.dispatch_event('on_mouse_motion', x, y, dx, dy) @PygletView.method('v@') def scrollWheel_(self, nsevent): x, y = getMousePosition(self, nsevent) scroll_x, scroll_y = getMouseDelta(nsevent) self._window.dispatch_event('on_mouse_scroll', x, y, scroll_x, scroll_y) @PygletView.method('v@') def mouseDown_(self, nsevent): x, y = getMousePosition(self, nsevent) buttons = mouse.LEFT modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_press', x, y, buttons, modifiers) @PygletView.method('v@') def mouseDragged_(self, nsevent): x, y = getMousePosition(self, nsevent) dx, dy = getMouseDelta(nsevent) buttons = mouse.LEFT modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_drag', x, y, dx, dy, buttons, modifiers) @PygletView.method('v@') def mouseUp_(self, nsevent): x, y = getMousePosition(self, nsevent) buttons = mouse.LEFT modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_release', x, y, buttons, modifiers) @PygletView.method('v@') def rightMouseDown_(self, nsevent): x, y = getMousePosition(self, nsevent) buttons = mouse.RIGHT modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_press', x, y, buttons, modifiers) @PygletView.method('v@') def rightMouseDragged_(self, nsevent): x, y = getMousePosition(self, nsevent) dx, dy = getMouseDelta(nsevent) buttons = mouse.RIGHT modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_drag', x, y, dx, dy, buttons, modifiers) @PygletView.method('v@') def rightMouseUp_(self, nsevent): x, y = getMousePosition(self, nsevent) buttons = mouse.RIGHT modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_release', x, y, buttons, modifiers) @PygletView.method('v@') def otherMouseDown_(self, nsevent): x, y = getMousePosition(self, nsevent) buttons = mouse.MIDDLE modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_press', x, y, buttons, modifiers) @PygletView.method('v@') def otherMouseDragged_(self, nsevent): x, y = getMousePosition(self, nsevent) dx, dy = getMouseDelta(nsevent) buttons = mouse.MIDDLE modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_drag', x, y, dx, dy, buttons, modifiers) @PygletView.method('v@') def otherMouseUp_(self, nsevent): x, y = getMousePosition(self, nsevent) buttons = mouse.MIDDLE modifiers = getModifiers(nsevent) self._window.dispatch_event('on_mouse_release', x, y, buttons, modifiers) @PygletView.method('v@') def mouseEntered_(self, nsevent): x, y = getMousePosition(self, nsevent) self._window._mouse_in_window = True # Don't call self._window.set_mouse_platform_visible() from here. # Better to do it from cursorUpdate: self._window.dispatch_event('on_mouse_enter', x, y) @PygletView.method('v@') def mouseExited_(self, nsevent): x, y = getMousePosition(self, nsevent) self._window._mouse_in_window = False if not self._window._is_mouse_exclusive: self._window.set_mouse_platform_visible() self._window.dispatch_event('on_mouse_leave', x, y) @PygletView.method('v@') def cursorUpdate_(self, nsevent): # Called when mouse cursor enters view. Unlike mouseEntered:, # this method will be called if the view appears underneath a # motionless mouse cursor, as can happen during window creation, # or when switching into fullscreen mode. # BUG: If the mouse enters the window via the resize control at the # the bottom right corner, the resize control will set the cursor # to the default arrow and screw up our cursor tracking. self._window._mouse_in_window = True if not self._window._is_mouse_exclusive: self._window.set_mouse_platform_visible() PygletView = ObjCClass('PygletView')
Python
from pyglet.libs.darwin.cocoapy import * from systemcursor import SystemCursor NSNotificationCenter = ObjCClass('NSNotificationCenter') NSApplication = ObjCClass('NSApplication') class PygletDelegate_Implementation(object): PygletDelegate = ObjCSubclass('NSObject', 'PygletDelegate') @PygletDelegate.method(b'@'+PyObjectEncoding) def initWithWindow_(self, window): self = ObjCInstance(send_super(self, 'init')) if not self: return None # CocoaWindow object. self._window = window window._nswindow.setDelegate_(self) # Register delegate for hide and unhide notifications so that we # can dispatch the corresponding pyglet events. notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver_selector_name_object_( self, get_selector('applicationDidHide:'), NSApplicationDidHideNotification, None) notificationCenter.addObserver_selector_name_object_( self, get_selector('applicationDidUnhide:'), NSApplicationDidUnhideNotification, None) # Flag set when we pause exclusive mouse mode if window loses key status. self.did_pause_exclusive_mouse = False return self @PygletDelegate.method('v') def dealloc(self): # Unregister delegate from notification center. notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.removeObserver_(self) self._window = None send_super(self, 'dealloc') @PygletDelegate.method('v@') def applicationDidHide_(self, notification): self._window.dispatch_event("on_hide") @PygletDelegate.method('v@') def applicationDidUnhide_(self, notification): if self._window._is_mouse_exclusive and quartz.CGCursorIsVisible(): # The cursor should be hidden, but for some reason it's not; # try to force the cursor to hide (without over-hiding). SystemCursor.unhide() SystemCursor.hide() pass self._window.dispatch_event("on_show") @PygletDelegate.method('B@') def windowShouldClose_(self, notification): # The method is not called if [NSWindow close] was used. self._window.dispatch_event("on_close") return False @PygletDelegate.method('v@') def windowDidMove_(self, notification): x, y = self._window.get_location() self._window.dispatch_event("on_move", x, y) @PygletDelegate.method('v@') def windowDidBecomeKey_(self, notification): # Restore exclusive mouse mode if it was active before we lost key status. if self.did_pause_exclusive_mouse: self._window.set_exclusive_mouse(True) self.did_pause_exclusive_mouse = False self._window._nswindow.setMovable_(True) # Mac OS 10.6 # Restore previous mouse visibility settings. self._window.set_mouse_platform_visible() self._window.dispatch_event("on_activate") @PygletDelegate.method('v@') def windowDidResignKey_(self, notification): # Pause exclusive mouse mode if it is active. if self._window._is_mouse_exclusive: self._window.set_exclusive_mouse(False) self.did_pause_exclusive_mouse = True # We need to prevent the window from being unintentionally dragged # (by the call to set_mouse_position in set_exclusive_mouse) when # the window is reactivated by clicking on its title bar. self._window._nswindow.setMovable_(False) # Mac OS X 10.6 # Make sure that cursor is visible. self._window.set_mouse_platform_visible(True) self._window.dispatch_event("on_deactivate") @PygletDelegate.method('v@') def windowDidMiniaturize_(self, notification): self._window.dispatch_event("on_hide") @PygletDelegate.method('v@') def windowDidDeminiaturize_(self, notification): if self._window._is_mouse_exclusive and quartz.CGCursorIsVisible(): # The cursor should be hidden, but for some reason it's not; # try to force the cursor to hide (without over-hiding). SystemCursor.unhide() SystemCursor.hide() pass self._window.dispatch_event("on_show") @PygletDelegate.method('v@') def windowDidExpose_(self, notification): self._window.dispatch_event("on_expose") @PygletDelegate.method('v@') def terminate_(self, sender): NSApp = NSApplication.sharedApplication() NSApp.terminate_(self) @PygletDelegate.method('B@') def validateMenuItem_(self, menuitem): # Disable quitting with command-q when in keyboard exclusive mode. if menuitem.action() == get_selector('terminate:'): return not self._window._is_keyboard_exclusive return True PygletDelegate = ObjCClass('PygletDelegate')
Python
from pyglet.libs.darwin.cocoapy import * # This class is a wrapper around NSCursor which prevents us from # sending too many hide or unhide messages in a row. Apparently # NSCursor treats them like retain/release messages, which can be # problematic when we are e.g. switching between window & fullscreen. class SystemCursor: cursor_is_hidden = False @classmethod def hide(cls): if not cls.cursor_is_hidden: send_message('NSCursor', 'hide') cls.cursor_is_hidden = True @classmethod def unhide(cls): if cls.cursor_is_hidden: send_message('NSCursor', 'unhide') cls.cursor_is_hidden = False
Python
import unicodedata from pyglet.window import key from pyglet.libs.darwin.cocoapy import * NSArray = ObjCClass('NSArray') NSApplication = ObjCClass('NSApplication') # This custom NSTextView subclass is used for capturing all of the # on_text, on_text_motion, and on_text_motion_select events. class PygletTextView_Implementation(object): PygletTextView = ObjCSubclass('NSTextView', 'PygletTextView') @PygletTextView.method(b'@'+PyObjectEncoding) def initWithCocoaWindow_(self, window): self = ObjCInstance(send_super(self, 'init')) if not self: return None self._window = window # Interpret tab and return as raw characters self.setFieldEditor_(False) self.empty_string = CFSTR("") return self @PygletTextView.method('v') def dealloc(self): self.empty_string.release() @PygletTextView.method('v@') def keyDown_(self, nsevent): array = NSArray.arrayWithObject_(nsevent) self.interpretKeyEvents_(array) @PygletTextView.method('v@') def insertText_(self, text): text = cfstring_to_string(text) self.setString_(self.empty_string) # Don't send control characters (tab, newline) as on_text events. if unicodedata.category(text[0]) != 'Cc': self._window.dispatch_event("on_text", text) @PygletTextView.method('v@') def insertNewline_(self, sender): # Distinguish between carriage return (u'\r') and enter (u'\x03'). # Only the return key press gets sent as an on_text event. event = NSApplication.sharedApplication().currentEvent() chars = event.charactersIgnoringModifiers() ch = unichr(chars.characterAtIndex_(0)) if ch == u'\r': self._window.dispatch_event("on_text", u'\r') @PygletTextView.method('v@') def moveUp_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_UP) @PygletTextView.method('v@') def moveDown_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_DOWN) @PygletTextView.method('v@') def moveLeft_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_LEFT) @PygletTextView.method('v@') def moveRight_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_RIGHT) @PygletTextView.method('v@') def moveWordLeft_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_PREVIOUS_WORD) @PygletTextView.method('v@') def moveWordRight_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_NEXT_WORD) @PygletTextView.method('v@') def moveToBeginningOfLine_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_BEGINNING_OF_LINE) @PygletTextView.method('v@') def moveToEndOfLine_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_END_OF_LINE) @PygletTextView.method('v@') def scrollPageUp_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_PREVIOUS_PAGE) @PygletTextView.method('v@') def scrollPageDown_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_NEXT_PAGE) @PygletTextView.method('v@') def scrollToBeginningOfDocument_(self, sender): # Mac OS X 10.6 self._window.dispatch_event("on_text_motion", key.MOTION_BEGINNING_OF_FILE) @PygletTextView.method('v@') def scrollToEndOfDocument_(self, sender): # Mac OS X 10.6 self._window.dispatch_event("on_text_motion", key.MOTION_END_OF_FILE) @PygletTextView.method('v@') def deleteBackward_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_BACKSPACE) @PygletTextView.method('v@') def deleteForward_(self, sender): self._window.dispatch_event("on_text_motion", key.MOTION_DELETE) @PygletTextView.method('v@') def moveUpAndModifySelection_(self, sender): self._window.dispatch_event("on_text_motion_select", key.MOTION_UP) @PygletTextView.method('v@') def moveDownAndModifySelection_(self, sender): self._window.dispatch_event("on_text_motion_select", key.MOTION_DOWN) @PygletTextView.method('v@') def moveLeftAndModifySelection_(self, sender): self._window.dispatch_event("on_text_motion_select", key.MOTION_LEFT) @PygletTextView.method('v@') def moveRightAndModifySelection_(self, sender): self._window.dispatch_event("on_text_motion_select", key.MOTION_RIGHT) @PygletTextView.method('v@') def moveWordLeftAndModifySelection_(self, sender): self._window.dispatch_event("on_text_motion_select", key.MOTION_PREVIOUS_WORD) @PygletTextView.method('v@') def moveWordRightAndModifySelection_(self, sender): self._window.dispatch_event("on_text_motion_select", key.MOTION_NEXT_WORD) @PygletTextView.method('v@') def moveToBeginningOfLineAndModifySelection_(self, sender): # Mac OS X 10.6 self._window.dispatch_event("on_text_motion_select", key.MOTION_BEGINNING_OF_LINE) @PygletTextView.method('v@') def moveToEndOfLineAndModifySelection_(self, sender): # Mac OS X 10.6 self._window.dispatch_event("on_text_motion_select", key.MOTION_END_OF_LINE) @PygletTextView.method('v@') def pageUpAndModifySelection_(self, sender): # Mac OS X 10.6 self._window.dispatch_event("on_text_motion_select", key.MOTION_PREVIOUS_PAGE) @PygletTextView.method('v@') def pageDownAndModifySelection_(self, sender): # Mac OS X 10.6 self._window.dispatch_event("on_text_motion_select", key.MOTION_NEXT_PAGE) @PygletTextView.method('v@') def moveToBeginningOfDocumentAndModifySelection_(self, sender): # Mac OS X 10.6 self._window.dispatch_event("on_text_motion_select", key.MOTION_BEGINNING_OF_FILE) @PygletTextView.method('v@') def moveToEndOfDocumentAndModifySelection_(self, sender): # Mac OS X 10.6 self._window.dispatch_event("on_text_motion_select", key.MOTION_END_OF_FILE) PygletTextView = ObjCClass('PygletTextView')
Python
from pyglet.libs.darwin.cocoapy import * class PygletWindow_Implementation(object): PygletWindow = ObjCSubclass('NSWindow', 'PygletWindow') @PygletWindow.method('B') def canBecomeKeyWindow(self): return True # When the window is being resized, it enters into a mini event loop that # only looks at mouseDragged and mouseUp events, blocking everything else. # Among other things, this makes it impossible to run an NSTimer to call the # idle() function in order to update the view during the resize. So we # override this method, called by the resizing event loop, and call the # idle() function from here. This *almost* works. I can't figure out what # is happening at the very beginning of a resize event. The NSView's # viewWillStartLiveResize method is called and then nothing happens until # the mouse is dragged. I think NSApplication's nextEventMatchingMask_etc # method is being called instead of this one. I don't really feel like # subclassing NSApplication just to fix this. Also, to prevent white flashes # while resizing, we must also call idle() from the view's reshape method. @PygletWindow.method(b'@'+NSUIntegerEncoding+b'@@B') def nextEventMatchingMask_untilDate_inMode_dequeue_(self, mask, date, mode, dequeue): if self.inLiveResize(): # Call the idle() method while we're stuck in a live resize event. from pyglet import app if app.event_loop is not None: app.event_loop.idle() event = send_super(self, 'nextEventMatchingMask:untilDate:inMode:dequeue:', mask, date, mode, dequeue, argtypes=[NSUInteger, c_void_p, c_void_p, c_bool]) if event.value == None: return 0 else: return event.value # Need this for set_size to not flash. @PygletWindow.method(b'd'+NSRectEncoding) def animationResizeTime_(self, newFrame): return 0.0 class PygletToolWindow_Implementation(object): PygletToolWindow = ObjCSubclass('NSPanel', 'PygletToolWindow') @PygletToolWindow.method(b'@'+NSUIntegerEncoding+b'@@B') def nextEventMatchingMask_untilDate_inMode_dequeue_(self, mask, date, mode, dequeue): if self.inLiveResize(): # Call the idle() method while we're stuck in a live resize event. from pyglet import app if app.event_loop is not None: app.event_loop.idle() event = send_super(self, 'nextEventMatchingMask:untilDate:inMode:dequeue:', mask, date, mode, dequeue, argtypes=[NSUInteger, c_void_p, c_void_p, c_bool]) if event.value == None: return 0 else: return event.value # Need this for set_size to not flash. @PygletToolWindow.method(b'd'+NSRectEncoding) def animationResizeTime_(self, newFrame): return 0.0 PygletWindow = ObjCClass('PygletWindow') PygletToolWindow = ObjCClass('PygletToolWindow')
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from ctypes import * import pyglet from pyglet.window import BaseWindow, WindowException from pyglet.window import MouseCursor, DefaultMouseCursor from pyglet.event import EventDispatcher from pyglet.canvas.cocoa import CocoaCanvas from pyglet.libs.darwin.cocoapy import * from systemcursor import SystemCursor from pyglet_delegate import PygletDelegate from pyglet_textview import PygletTextView from pyglet_window import PygletWindow, PygletToolWindow from pyglet_view import PygletView NSApplication = ObjCClass('NSApplication') NSCursor = ObjCClass('NSCursor') NSAutoreleasePool = ObjCClass('NSAutoreleasePool') NSColor = ObjCClass('NSColor') NSEvent = ObjCClass('NSEvent') NSImage = ObjCClass('NSImage') class CocoaMouseCursor(MouseCursor): drawable = False def __init__(self, cursorName): # cursorName is a string identifying one of the named default NSCursors # e.g. 'pointingHandCursor', and can be sent as message to NSCursor class. self.cursorName = cursorName def set(self): cursor = getattr(NSCursor, self.cursorName)() cursor.set() class CocoaWindow(BaseWindow): # NSWindow instance. _nswindow = None # Delegate object. _delegate = None # Window properties _minimum_size = None _maximum_size = None _is_mouse_exclusive = False _mouse_platform_visible = True _mouse_ignore_motion = False _is_keyboard_exclusive = False # Flag set during close() method. _was_closed = False # NSWindow style masks. _style_masks = { BaseWindow.WINDOW_STYLE_DEFAULT: NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask, BaseWindow.WINDOW_STYLE_DIALOG: NSTitledWindowMask | NSClosableWindowMask, BaseWindow.WINDOW_STYLE_TOOL: NSTitledWindowMask | NSClosableWindowMask | NSUtilityWindowMask, BaseWindow.WINDOW_STYLE_BORDERLESS: NSBorderlessWindowMask, } def _recreate(self, changes): if ('context' in changes): self.context.set_current() if 'fullscreen' in changes: if not self._fullscreen: # leaving fullscreen self.screen.release_display() self._create() def _create(self): # Create a temporary autorelease pool for this method. pool = NSAutoreleasePool.alloc().init() if self._nswindow: # The window is about the be recreated so destroy everything # associated with the old window, then destroy the window itself. nsview = self.canvas.nsview self.canvas = None self._nswindow.orderOut_(None) self._nswindow.close() self.context.detach() self._nswindow.release() self._nswindow = None nsview.release() self._delegate.release() self._delegate = None # Determine window parameters. content_rect = NSMakeRect(0, 0, self._width, self._height) WindowClass = PygletWindow if self._fullscreen: style_mask = NSBorderlessWindowMask else: if self._style not in self._style_masks: self._style = self.WINDOW_STYLE_DEFAULT style_mask = self._style_masks[self._style] if self._resizable: style_mask |= NSResizableWindowMask if self._style == BaseWindow.WINDOW_STYLE_TOOL: WindowClass = PygletToolWindow # First create an instance of our NSWindow subclass. # FIX ME: # Need to use this initializer to have any hope of multi-monitor support. # But currently causes problems on Mac OS X Lion. So for now, we initialize the # window without including screen information. # # self._nswindow = WindowClass.alloc().initWithContentRect_styleMask_backing_defer_screen_( # content_rect, # contentRect # style_mask, # styleMask # NSBackingStoreBuffered, # backing # False, # defer # self.screen.get_nsscreen()) # screen self._nswindow = WindowClass.alloc().initWithContentRect_styleMask_backing_defer_( content_rect, # contentRect style_mask, # styleMask NSBackingStoreBuffered, # backing False) # defer if self._fullscreen: # BUG: I suspect that this doesn't do the right thing when using # multiple monitors (which would be to go fullscreen on the monitor # where the window is located). However I've no way to test. blackColor = NSColor.blackColor() self._nswindow.setBackgroundColor_(blackColor) self._nswindow.setOpaque_(True) self.screen.capture_display() self._nswindow.setLevel_(quartz.CGShieldingWindowLevel()) self.context.set_full_screen() self._center_window() self._mouse_in_window = True else: self._set_nice_window_location() self._mouse_in_window = self._mouse_in_content_rect() # Then create a view and set it as our NSWindow's content view. self._nsview = PygletView.alloc().initWithFrame_cocoaWindow_(content_rect, self) self._nswindow.setContentView_(self._nsview) self._nswindow.makeFirstResponder_(self._nsview) # Create a canvas with the view as its drawable and attach context to it. self.canvas = CocoaCanvas(self.display, self.screen, self._nsview) self.context.attach(self.canvas) # Configure the window. self._nswindow.setAcceptsMouseMovedEvents_(True) self._nswindow.setReleasedWhenClosed_(False) self._nswindow.useOptimizedDrawing_(True) self._nswindow.setPreservesContentDuringLiveResize_(False) # Set the delegate. self._delegate = PygletDelegate.alloc().initWithWindow_(self) # Configure CocoaWindow. self.set_caption(self._caption) if self._minimum_size is not None: self.set_minimum_size(*self._minimum_size) if self._maximum_size is not None: self.set_maximum_size(*self._maximum_size) self.context.update_geometry() self.switch_to() self.set_vsync(self._vsync) self.set_visible(self._visible) pool.drain() def _set_nice_window_location(self): # Construct a list of all visible windows that aren't us. visible_windows = [ win for win in pyglet.app.windows if win is not self and win._nswindow and win._nswindow.isVisible() ] # If there aren't any visible windows, then center this window. if not visible_windows: self._center_window() # Otherwise, cascade from last window in list. else: point = visible_windows[-1]._nswindow.cascadeTopLeftFromPoint_(NSZeroPoint) self._nswindow.cascadeTopLeftFromPoint_(point) def _center_window(self): # [NSWindow center] does not move the window to a true center position # and also always moves the window to the main display. x = self.screen.x + int((self.screen.width - self._width)/2) y = self.screen.y + int((self.screen.height - self._height)/2) self._nswindow.setFrameOrigin_(NSPoint(x, y)) def close(self): # If we've already gone through this once, don't do it again. if self._was_closed: return # Create a temporary autorelease pool for this method. pool = NSAutoreleasePool.new() # Restore cursor visibility self.set_mouse_platform_visible(True) self.set_exclusive_mouse(False) self.set_exclusive_keyboard(False) # Remove the delegate object if self._delegate: self._nswindow.setDelegate_(None) self._delegate.release() self._delegate = None # Remove window from display and remove its view. if self._nswindow: self._nswindow.orderOut_(None) self._nswindow.setContentView_(None) self._nswindow.close() # Restore screen mode. This also releases the display # if it was captured for fullscreen mode. self.screen.restore_mode() # Remove view from canvas and then remove canvas. if self.canvas: self.canvas.nsview.release() self.canvas.nsview = None self.canvas = None # Do this last, so that we don't see white flash # when exiting application from fullscreen mode. super(CocoaWindow, self).close() self._was_closed = True pool.drain() def switch_to(self): if self.context: self.context.set_current() def flip(self): self.draw_mouse_cursor() if self.context: self.context.flip() def dispatch_events(self): self._allow_dispatch_event = True # Process all pyglet events. self.dispatch_pending_events() event = True # Dequeue and process all of the pending Cocoa events. pool = NSAutoreleasePool.new() NSApp = NSApplication.sharedApplication() while event and self._nswindow and self._context: event = NSApp.nextEventMatchingMask_untilDate_inMode_dequeue_( NSAnyEventMask, None, NSEventTrackingRunLoopMode, True) if event: event_type = event.type() # Pass on all events. NSApp.sendEvent_(event) # And resend key events to special handlers. if event_type == NSKeyDown and not event.isARepeat(): NSApp.sendAction_to_from_(get_selector('pygletKeyDown:'), None, event) elif event_type == NSKeyUp: NSApp.sendAction_to_from_(get_selector('pygletKeyUp:'), None, event) elif event_type == NSFlagsChanged: NSApp.sendAction_to_from_(get_selector('pygletFlagsChanged:'), None, event) NSApp.updateWindows() pool.drain() self._allow_dispatch_event = False def dispatch_pending_events(self): while self._event_queue: event = self._event_queue.pop(0) EventDispatcher.dispatch_event(self, *event) def set_caption(self, caption): self._caption = caption if self._nswindow is not None: self._nswindow.setTitle_(get_NSString(caption)) def set_icon(self, *images): # Only use the biggest image from the list. max_image = images[0] for img in images: if img.width > max_image.width and img.height > max_image.height: max_image = img # Grab image data from pyglet image. image = max_image.get_image_data() format = 'ARGB' bytesPerRow = len(format) * image.width data = image.get_data(format, -bytesPerRow) # Use image data to create a data provider. # Using CGDataProviderCreateWithData crashes PyObjC 2.2b3, so we create # a CFDataRef object first and use it to create the data provider. cfdata = c_void_p(cf.CFDataCreate(None, data, len(data))) provider = c_void_p(quartz.CGDataProviderCreateWithCFData(cfdata)) colorSpace = c_void_p(quartz.CGColorSpaceCreateDeviceRGB()) # Then create a CGImage from the provider. cgimage = c_void_p(quartz.CGImageCreate( image.width, image.height, 8, 32, bytesPerRow, colorSpace, kCGImageAlphaFirst, provider, None, True, kCGRenderingIntentDefault)) if not cgimage: return cf.CFRelease(cfdata) quartz.CGDataProviderRelease(provider) quartz.CGColorSpaceRelease(colorSpace) # Turn the CGImage into an NSImage. size = NSMakeSize(image.width, image.height) nsimage = NSImage.alloc().initWithCGImage_size_(cgimage, size) if not nsimage: return # And finally set the app icon. NSApp = NSApplication.sharedApplication() NSApp.setApplicationIconImage_(nsimage) nsimage.release() def get_location(self): window_frame = self._nswindow.frame() rect = self._nswindow.contentRectForFrameRect_(window_frame) screen_frame = self._nswindow.screen().frame() screen_width = int(screen_frame.size.width) screen_height = int(screen_frame.size.height) return int(rect.origin.x), int(screen_height - rect.origin.y - rect.size.height) def set_location(self, x, y): window_frame = self._nswindow.frame() rect = self._nswindow.contentRectForFrameRect_(window_frame) screen_frame = self._nswindow.screen().frame() screen_width = int(screen_frame.size.width) screen_height = int(screen_frame.size.height) origin = NSPoint(x, screen_height - y - rect.size.height) self._nswindow.setFrameOrigin_(origin) def get_size(self): window_frame = self._nswindow.frame() rect = self._nswindow.contentRectForFrameRect_(window_frame) return int(rect.size.width), int(rect.size.height) def set_size(self, width, height): if self._fullscreen: raise WindowException('Cannot set size of fullscreen window.') self._width = max(1, int(width)) self._height = max(1, int(height)) # Move frame origin down so that top-left corner of window doesn't move. window_frame = self._nswindow.frame() rect = self._nswindow.contentRectForFrameRect_(window_frame) rect.origin.y += rect.size.height - self._height rect.size.width = self._width rect.size.height = self._height new_frame = self._nswindow.frameRectForContentRect_(rect) # The window background flashes when the frame size changes unless it's # animated, but we can set the window's animationResizeTime to zero. is_visible = self._nswindow.isVisible() self._nswindow.setFrame_display_animate_(new_frame, True, is_visible) def set_minimum_size(self, width, height): self._minimum_size = NSSize(width, height) if self._nswindow is not None: self._nswindow.setContentMinSize_(self._minimum_size) def set_maximum_size(self, width, height): self._maximum_size = NSSize(width, height) if self._nswindow is not None: self._nswindow.setContentMaxSize_(self._maximum_size) def activate(self): if self._nswindow is not None: NSApp = NSApplication.sharedApplication() NSApp.activateIgnoringOtherApps_(True) self._nswindow.makeKeyAndOrderFront_(None) def set_visible(self, visible=True): self._visible = visible if self._nswindow is not None: if visible: # Not really sure why on_resize needs to be here, # but it's what pyglet wants. self.dispatch_event('on_resize', self._width, self._height) self.dispatch_event('on_show') self.dispatch_event('on_expose') self._nswindow.makeKeyAndOrderFront_(None) else: self._nswindow.orderOut_(None) def minimize(self): self._mouse_in_window = False if self._nswindow is not None: self._nswindow.miniaturize_(None) def maximize(self): if self._nswindow is not None: self._nswindow.zoom_(None) def set_vsync(self, vsync): if pyglet.options['vsync'] is not None: vsync = pyglet.options['vsync'] self._vsync = vsync # _recreate depends on this if self.context: self.context.set_vsync(vsync) def _mouse_in_content_rect(self): # Returns true if mouse is inside the window's content rectangle. # Better to use this method to check manually rather than relying # on instance variables that may not be set correctly. point = NSEvent.mouseLocation() window_frame = self._nswindow.frame() rect = self._nswindow.contentRectForFrameRect_(window_frame) return foundation.NSMouseInRect(point, rect, False) def set_mouse_platform_visible(self, platform_visible=None): # When the platform_visible argument is supplied with a boolean, then this # method simply sets whether or not the platform mouse cursor is visible. if platform_visible is not None: if platform_visible: SystemCursor.unhide() else: SystemCursor.hide() # But if it has been called without an argument, it turns into # a completely different function. Now we are trying to figure out # whether or not the mouse *should* be visible, and if so, what it should # look like. else: # If we are in mouse exclusive mode, then hide the mouse cursor. if self._is_mouse_exclusive: SystemCursor.hide() # If we aren't inside the window, then always show the mouse # and make sure that it is the default cursor. elif not self._mouse_in_content_rect(): NSCursor.arrowCursor().set() SystemCursor.unhide() # If we are in the window, then what we do depends on both # the current pyglet-set visibility setting for the mouse and # the type of the mouse cursor. If the cursor has been hidden # in the window with set_mouse_visible() then don't show it. elif not self._mouse_visible: SystemCursor.hide() # If the mouse is set as a system-defined cursor, then we # need to set the cursor and show the mouse. # *** FIX ME *** elif isinstance(self._mouse_cursor, CocoaMouseCursor): self._mouse_cursor.set() SystemCursor.unhide() # If the mouse cursor is drawable, then it we need to hide # the system mouse cursor, so that the cursor can draw itself. elif self._mouse_cursor.drawable: SystemCursor.hide() # Otherwise, show the default cursor. else: NSCursor.arrowCursor().set() SystemCursor.unhide() def get_system_mouse_cursor(self, name): # It would make a lot more sense for most of this code to be # inside the CocoaMouseCursor class, but all of the CURSOR_xxx # constants are defined as properties of BaseWindow. if name == self.CURSOR_DEFAULT: return DefaultMouseCursor() cursors = { self.CURSOR_CROSSHAIR: 'crosshairCursor', self.CURSOR_HAND: 'pointingHandCursor', self.CURSOR_HELP: 'arrowCursor', self.CURSOR_NO: 'operationNotAllowedCursor', # Mac OS 10.6 self.CURSOR_SIZE: 'arrowCursor', self.CURSOR_SIZE_UP: 'resizeUpCursor', self.CURSOR_SIZE_UP_RIGHT: 'arrowCursor', self.CURSOR_SIZE_RIGHT: 'resizeRightCursor', self.CURSOR_SIZE_DOWN_RIGHT: 'arrowCursor', self.CURSOR_SIZE_DOWN: 'resizeDownCursor', self.CURSOR_SIZE_DOWN_LEFT: 'arrowCursor', self.CURSOR_SIZE_LEFT: 'resizeLeftCursor', self.CURSOR_SIZE_UP_LEFT: 'arrowCursor', self.CURSOR_SIZE_UP_DOWN: 'resizeUpDownCursor', self.CURSOR_SIZE_LEFT_RIGHT: 'resizeLeftRightCursor', self.CURSOR_TEXT: 'IBeamCursor', self.CURSOR_WAIT: 'arrowCursor', # No wristwatch cursor in Cocoa self.CURSOR_WAIT_ARROW: 'arrowCursor', # No wristwatch cursor in Cocoa } if name not in cursors: raise RuntimeError('Unknown cursor name "%s"' % name) return CocoaMouseCursor(cursors[name]) def set_mouse_position(self, x, y, absolute=False): if absolute: # If absolute, then x, y is given in global display coordinates # which sets (0,0) at top left corner of main display. It is possible # to warp the mouse position to a point inside of another display. quartz.CGWarpMouseCursorPosition(CGPoint(x,y)) else: # Window-relative coordinates: (x, y) are given in window coords # with (0,0) at bottom-left corner of window and y up. We find # which display the window is in and then convert x, y into local # display coords where (0,0) is now top-left of display and y down. screenInfo = self._nswindow.screen().deviceDescription() displayID = screenInfo.objectForKey_(get_NSString('NSScreenNumber')) displayID = displayID.intValue() displayBounds = quartz.CGDisplayBounds(displayID) frame = self._nswindow.frame() windowOrigin = frame.origin x += windowOrigin.x y = displayBounds.size.height - windowOrigin.y - y quartz.CGDisplayMoveCursorToPoint(displayID, NSPoint(x,y)) def set_exclusive_mouse(self, exclusive=True): self._is_mouse_exclusive = exclusive if exclusive: # Skip the next motion event, which would return a large delta. self._mouse_ignore_motion = True # Move mouse to center of window. frame = self._nswindow.frame() width, height = frame.size.width, frame.size.height self.set_mouse_position(width/2, height/2) quartz.CGAssociateMouseAndMouseCursorPosition(False) else: quartz.CGAssociateMouseAndMouseCursorPosition(True) # Update visibility of mouse cursor. self.set_mouse_platform_visible() def set_exclusive_keyboard(self, exclusive=True): # http://developer.apple.com/mac/library/technotes/tn2002/tn2062.html # http://developer.apple.com/library/mac/#technotes/KioskMode/ # BUG: System keys like F9 or command-tab are disabled, however # pyglet also does not receive key press events for them. # This flag is queried by window delegate to determine whether # the quit menu item is active. self._is_keyboard_exclusive = exclusive if exclusive: # "Be nice! Don't disable force-quit!" # -- Patrick Swayze, Road House (1989) options = NSApplicationPresentationHideDock | \ NSApplicationPresentationHideMenuBar | \ NSApplicationPresentationDisableProcessSwitching | \ NSApplicationPresentationDisableHideApplication else: options = NSApplicationPresentationDefault NSApp = NSApplication.sharedApplication() NSApp.setPresentationOptions_(options)
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Events for `pyglet.window`. See `Window` for a description of the window event types. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import sys from pyglet.window import key from pyglet.window import mouse class WindowExitHandler(object): '''Determine if the window should be closed. This event handler watches for the ESC key or the window close event and sets `self.has_exit` to True when either is pressed. An instance of this class is automatically attached to all new `pyglet.window.Window` objects. :deprecated: This class's functionality is provided directly on `Window` in pyglet 1.1. :Ivariables: `has_exit` : bool True if the user wants to close the window. ''' has_exit = False def on_close(self): self.has_exit = True def on_key_press(self, symbol, modifiers): if symbol == key.ESCAPE: self.has_exit = True class WindowEventLogger(object): '''Print all events to a file. When this event handler is added to a window it prints out all events and their parameters; useful for debugging or discovering which events you need to handle. Example:: win = window.Window() win.push_handlers(WindowEventLogger()) ''' def __init__(self, logfile=None): '''Create a `WindowEventLogger` which writes to `logfile`. :Parameters: `logfile` : file-like object The file to write to. If unspecified, stdout will be used. ''' if logfile is None: logfile = sys.stdout self.file = logfile def on_key_press(self, symbol, modifiers): print >> self.file, 'on_key_press(symbol=%s, modifiers=%s)' % ( key.symbol_string(symbol), key.modifiers_string(modifiers)) def on_key_release(self, symbol, modifiers): print >> self.file, 'on_key_release(symbol=%s, modifiers=%s)' % ( key.symbol_string(symbol), key.modifiers_string(modifiers)) def on_text(self, text): print >> self.file, 'on_text(text=%r)' % text def on_text_motion(self, motion): print >> self.file, 'on_text_motion(motion=%s)' % ( key.motion_string(motion)) def on_text_motion_select(self, motion): print >> self.file, 'on_text_motion_select(motion=%s)' % ( key.motion_string(motion)) def on_mouse_motion(self, x, y, dx, dy): print >> self.file, 'on_mouse_motion(x=%d, y=%d, dx=%d, dy=%d)' % ( x, y, dx, dy) def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): print >> self.file, 'on_mouse_drag(x=%d, y=%d, dx=%d, dy=%d, '\ 'buttons=%s, modifiers=%s)' % ( x, y, dx, dy, mouse.buttons_string(buttons), key.modifiers_string(modifiers)) def on_mouse_press(self, x, y, button, modifiers): print >> self.file, 'on_mouse_press(x=%d, y=%d, button=%r, '\ 'modifiers=%s)' % (x, y, mouse.buttons_string(button), key.modifiers_string(modifiers)) def on_mouse_release(self, x, y, button, modifiers): print >> self.file, 'on_mouse_release(x=%d, y=%d, button=%r, '\ 'modifiers=%s)' % (x, y, mouse.buttons_string(button), key.modifiers_string(modifiers)) def on_mouse_scroll(self, x, y, dx, dy): print >> self.file, 'on_mouse_scroll(x=%f, y=%f, dx=%f, dy=%f)' % ( x, y, dx, dy) def on_close(self): print >> self.file, 'on_close()' def on_mouse_enter(self, x, y): print >> self.file, 'on_mouse_enter(x=%d, y=%d)' % (x, y) def on_mouse_leave(self, x, y): print >> self.file, 'on_mouse_leave(x=%d, y=%d)' % (x, y) def on_expose(self): print >> self.file, 'on_expose()' def on_resize(self, width, height): print >> self.file, 'on_resize(width=%d, height=%d)' % (width, height) def on_move(self, x, y): print >> self.file, 'on_move(x=%d, y=%d)' % (x, y) def on_activate(self): print >> self.file, 'on_activate()' def on_deactivate(self): print >> self.file, 'on_deactivate()' def on_show(self): print >> self.file, 'on_show()' def on_hide(self): print >> self.file, 'on_hide()' def on_context_lost(self): print >> self.file, 'on_context_lost()' def on_context_state_lost(self): print >> self.file, 'on_context_state_lost()' def on_draw(self): print >> self.file, 'on_draw()'
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Key constants and utilities for pyglet.window. Usage:: from pyglet.window import Window from pyglet.window import key window = Window() @window.event def on_key_press(symbol, modifiers): # Symbolic names: if symbol == key.RETURN: # Alphabet keys: elif symbol == key.Z: # Number keys: elif symbol == key._1: # Number keypad keys: elif symbol == key.NUM_1: # Modifiers: if modifiers & key.MOD_CTRL: ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' class KeyStateHandler(dict): '''Simple handler that tracks the state of keys on the keyboard. If a key is pressed then this handler holds a True value for it. For example:: >>> win = window.Window >>> keyboard = key.KeyStateHandler() >>> win.push_handlers(keyboard) # Hold down the "up" arrow... >>> keyboard[key.UP] True >>> keyboard[key.DOWN] False ''' def on_key_press(self, symbol, modifiers): self[symbol] = True def on_key_release(self, symbol, modifiers): self[symbol] = False def __getitem__(self, key): return self.get(key, False) def modifiers_string(modifiers): '''Return a string describing a set of modifiers. Example:: >>> modifiers_string(MOD_SHIFT | MOD_CTRL) 'MOD_SHIFT|MOD_CTRL' :Parameters: `modifiers` : int Bitwise combination of modifier constants. :rtype: str ''' mod_names = [] if modifiers & MOD_SHIFT: mod_names.append('MOD_SHIFT') if modifiers & MOD_CTRL: mod_names.append('MOD_CTRL') if modifiers & MOD_ALT: mod_names.append('MOD_ALT') if modifiers & MOD_CAPSLOCK: mod_names.append('MOD_CAPSLOCK') if modifiers & MOD_NUMLOCK: mod_names.append('MOD_NUMLOCK') if modifiers & MOD_SCROLLLOCK: mod_names.append('MOD_SCROLLLOCK') if modifiers & MOD_COMMAND: mod_names.append('MOD_COMMAND') if modifiers & MOD_OPTION: mod_names.append('MOD_OPTION') if modifiers & MOD_FUNCTION: mod_names.append('MOD_FUNCTION') return '|'.join(mod_names) def symbol_string(symbol): '''Return a string describing a key symbol. Example:: >>> symbol_string(BACKSPACE) 'BACKSPACE' :Parameters: `symbol` : int Symbolic key constant. :rtype: str ''' if symbol < 1 << 32: return _key_names.get(symbol, str(symbol)) else: return 'user_key(%x)' % (symbol >> 32) def motion_string(motion): '''Return a string describing a text motion. Example:: >>> motion_string(MOTION_NEXT_WORD): 'MOTION_NEXT_WORD' :Parameters: `motion` : int Text motion constant. :rtype: str ''' return _motion_names.get(motion, str(motion)) def user_key(scancode): '''Return a key symbol for a key not supported by pyglet. This can be used to map virtual keys or scancodes from unsupported keyboard layouts into a machine-specific symbol. The symbol will be meaningless on any other machine, or under a different keyboard layout. Applications should use user-keys only when user explicitly binds them (for example, mapping keys to actions in a game options screen). ''' assert scancode > 0 return scancode << 32 # Modifier mask constants MOD_SHIFT = 1 << 0 MOD_CTRL = 1 << 1 MOD_ALT = 1 << 2 MOD_CAPSLOCK = 1 << 3 MOD_NUMLOCK = 1 << 4 MOD_WINDOWS = 1 << 5 MOD_COMMAND = 1 << 6 MOD_OPTION = 1 << 7 MOD_SCROLLLOCK = 1 << 8 MOD_FUNCTION = 1 << 9 #: Accelerator modifier. On Windows and Linux, this is ``MOD_CTRL``, on #: Mac OS X it's ``MOD_COMMAND``. MOD_ACCEL = MOD_CTRL from pyglet import compat_platform if compat_platform == 'darwin': MOD_ACCEL = MOD_COMMAND # Key symbol constants # ASCII commands BACKSPACE = 0xff08 TAB = 0xff09 LINEFEED = 0xff0a CLEAR = 0xff0b RETURN = 0xff0d ENTER = 0xff0d # synonym PAUSE = 0xff13 SCROLLLOCK = 0xff14 SYSREQ = 0xff15 ESCAPE = 0xff1b SPACE = 0xff20 # Cursor control and motion HOME = 0xff50 LEFT = 0xff51 UP = 0xff52 RIGHT = 0xff53 DOWN = 0xff54 PAGEUP = 0xff55 PAGEDOWN = 0xff56 END = 0xff57 BEGIN = 0xff58 # Misc functions DELETE = 0xffff SELECT = 0xff60 PRINT = 0xff61 EXECUTE = 0xff62 INSERT = 0xff63 UNDO = 0xff65 REDO = 0xff66 MENU = 0xff67 FIND = 0xff68 CANCEL = 0xff69 HELP = 0xff6a BREAK = 0xff6b MODESWITCH = 0xff7e SCRIPTSWITCH = 0xff7e FUNCTION = 0xffd2 # Text motion constants: these are allowed to clash with key constants MOTION_UP = UP MOTION_RIGHT = RIGHT MOTION_DOWN = DOWN MOTION_LEFT = LEFT MOTION_NEXT_WORD = 1 MOTION_PREVIOUS_WORD = 2 MOTION_BEGINNING_OF_LINE = 3 MOTION_END_OF_LINE = 4 MOTION_NEXT_PAGE = PAGEDOWN MOTION_PREVIOUS_PAGE = PAGEUP MOTION_BEGINNING_OF_FILE = 5 MOTION_END_OF_FILE = 6 MOTION_BACKSPACE = BACKSPACE MOTION_DELETE = DELETE # Number pad NUMLOCK = 0xff7f NUM_SPACE = 0xff80 NUM_TAB = 0xff89 NUM_ENTER = 0xff8d NUM_F1 = 0xff91 NUM_F2 = 0xff92 NUM_F3 = 0xff93 NUM_F4 = 0xff94 NUM_HOME = 0xff95 NUM_LEFT = 0xff96 NUM_UP = 0xff97 NUM_RIGHT = 0xff98 NUM_DOWN = 0xff99 NUM_PRIOR = 0xff9a NUM_PAGE_UP = 0xff9a NUM_NEXT = 0xff9b NUM_PAGE_DOWN = 0xff9b NUM_END = 0xff9c NUM_BEGIN = 0xff9d NUM_INSERT = 0xff9e NUM_DELETE = 0xff9f NUM_EQUAL = 0xffbd NUM_MULTIPLY = 0xffaa NUM_ADD = 0xffab NUM_SEPARATOR = 0xffac NUM_SUBTRACT = 0xffad NUM_DECIMAL = 0xffae NUM_DIVIDE = 0xffaf NUM_0 = 0xffb0 NUM_1 = 0xffb1 NUM_2 = 0xffb2 NUM_3 = 0xffb3 NUM_4 = 0xffb4 NUM_5 = 0xffb5 NUM_6 = 0xffb6 NUM_7 = 0xffb7 NUM_8 = 0xffb8 NUM_9 = 0xffb9 # Function keys F1 = 0xffbe F2 = 0xffbf F3 = 0xffc0 F4 = 0xffc1 F5 = 0xffc2 F6 = 0xffc3 F7 = 0xffc4 F8 = 0xffc5 F9 = 0xffc6 F10 = 0xffc7 F11 = 0xffc8 F12 = 0xffc9 F13 = 0xffca F14 = 0xffcb F15 = 0xffcc F16 = 0xffcd F17 = 0xffce F18 = 0xffcf F19 = 0xffd0 F20 = 0xffd1 # Modifiers LSHIFT = 0xffe1 RSHIFT = 0xffe2 LCTRL = 0xffe3 RCTRL = 0xffe4 CAPSLOCK = 0xffe5 LMETA = 0xffe7 RMETA = 0xffe8 LALT = 0xffe9 RALT = 0xffea LWINDOWS = 0xffeb RWINDOWS = 0xffec LCOMMAND = 0xffed RCOMMAND = 0xffee LOPTION = 0xffef ROPTION = 0xfff0 # Latin-1 SPACE = 0x020 EXCLAMATION = 0x021 DOUBLEQUOTE = 0x022 HASH = 0x023 POUND = 0x023 # synonym DOLLAR = 0x024 PERCENT = 0x025 AMPERSAND = 0x026 APOSTROPHE = 0x027 PARENLEFT = 0x028 PARENRIGHT = 0x029 ASTERISK = 0x02a PLUS = 0x02b COMMA = 0x02c MINUS = 0x02d PERIOD = 0x02e SLASH = 0x02f _0 = 0x030 _1 = 0x031 _2 = 0x032 _3 = 0x033 _4 = 0x034 _5 = 0x035 _6 = 0x036 _7 = 0x037 _8 = 0x038 _9 = 0x039 COLON = 0x03a SEMICOLON = 0x03b LESS = 0x03c EQUAL = 0x03d GREATER = 0x03e QUESTION = 0x03f AT = 0x040 BRACKETLEFT = 0x05b BACKSLASH = 0x05c BRACKETRIGHT = 0x05d ASCIICIRCUM = 0x05e UNDERSCORE = 0x05f GRAVE = 0x060 QUOTELEFT = 0x060 A = 0x061 B = 0x062 C = 0x063 D = 0x064 E = 0x065 F = 0x066 G = 0x067 H = 0x068 I = 0x069 J = 0x06a K = 0x06b L = 0x06c M = 0x06d N = 0x06e O = 0x06f P = 0x070 Q = 0x071 R = 0x072 S = 0x073 T = 0x074 U = 0x075 V = 0x076 W = 0x077 X = 0x078 Y = 0x079 Z = 0x07a BRACELEFT = 0x07b BAR = 0x07c BRACERIGHT = 0x07d ASCIITILDE = 0x07e _key_names = {} _motion_names = {} for _name, _value in locals().copy().items(): if _name[:2] != '__' and _name.upper() == _name and \ not _name.startswith('MOD_'): if _name.startswith('MOTION_'): _motion_names[_value] = _name else: _key_names[_value] = _name
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Windowing and user-interface events. This module allows applications to create and display windows with an OpenGL context. Windows can be created with a variety of border styles or set fullscreen. You can register event handlers for keyboard, mouse and window events. For games and kiosks you can also restrict the input to your windows, for example disabling users from switching away from the application with certain key combinations or capturing and hiding the mouse. Getting started --------------- Call the Window constructor to create a new window:: from pyglet.window import Window win = Window(width=640, height=480) Attach your own event handlers:: @win.event def on_key_press(symbol, modifiers): # ... handle this event ... Place drawing code for the window within the `Window.on_draw` event handler:: @win.event def on_draw(): # ... drawing code ... Call `pyglet.app.run` to enter the main event loop (by default, this returns when all open windows are closed):: from pyglet import app app.run() Creating a game window ---------------------- Use `Window.set_exclusive_mouse` to hide the mouse cursor and receive relative mouse movement events. Specify ``fullscreen=True`` as a keyword argument to the `Window` constructor to render to the entire screen rather than opening a window:: win = Window(fullscreen=True) win.set_exclusive_mouse() Working with multiple screens ----------------------------- By default, fullscreen windows are opened on the primary display (typically set by the user in their operating system settings). You can retrieve a list of attached screens and select one manually if you prefer. This is useful for opening a fullscreen window on each screen:: display = window.get_platform().get_default_display() screens = display.get_screens() windows = [] for screen in screens: windows.append(window.Window(fullscreen=True, screen=screen)) Specifying a screen has no effect if the window is not fullscreen. Specifying the OpenGL context properties ---------------------------------------- Each window has its own context which is created when the window is created. You can specify the properties of the context before it is created by creating a "template" configuration:: from pyglet import gl # Create template config config = gl.Config() config.stencil_size = 8 config.aux_buffers = 4 # Create a window using this config win = window.Window(config=config) To determine if a given configuration is supported, query the screen (see above, "Working with multiple screens"):: configs = screen.get_matching_configs(config) if not configs: # ... config is not supported else: win = window.Window(config=configs[0]) ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import pprint import sys import pyglet from pyglet import gl from pyglet.gl import gl_info from pyglet.event import EventDispatcher import pyglet.window.key import pyglet.window.event _is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc class WindowException(Exception): '''The root exception for all window-related errors.''' pass #XXX class NoSuchDisplayException(WindowException): '''An exception indicating the requested display is not available.''' pass class NoSuchConfigException(WindowException): '''An exception indicating the requested configuration is not available.''' pass class NoSuchScreenModeException(WindowException): '''An exception indicating the requested screen resolution could not be met.''' pass class MouseCursorException(WindowException): '''The root exception for all mouse cursor-related errors.''' pass class MouseCursor(object): '''An abstract mouse cursor.''' #: Indicates if the cursor is drawn using OpenGL. This is True #: for all mouse cursors except system cursors. drawable = True def draw(self, x, y): '''Abstract render method. The cursor should be drawn with the "hot" spot at the given coordinates. The projection is set to the pyglet default (i.e., orthographic in window-space), however no other aspects of the state can be assumed. :Parameters: `x` : int X coordinate of the mouse pointer's hot spot. `y` : int Y coordinate of the mouse pointer's hot spot. ''' raise NotImplementedError('abstract') class DefaultMouseCursor(MouseCursor): '''The default mouse cursor used by the operating system.''' drawable = False class ImageMouseCursor(MouseCursor): '''A user-defined mouse cursor created from an image. Use this class to create your own mouse cursors and assign them to windows. There are no constraints on the image size or format. ''' drawable = True def __init__(self, image, hot_x=0, hot_y=0): '''Create a mouse cursor from an image. :Parameters: `image` : `pyglet.image.AbstractImage` Image to use for the mouse cursor. It must have a valid ``texture`` attribute. `hot_x` : int X coordinate of the "hot" spot in the image relative to the image's anchor. `hot_y` : int Y coordinate of the "hot" spot in the image, relative to the image's anchor. ''' self.texture = image.get_texture() self.hot_x = hot_x self.hot_y = hot_y def draw(self, x, y): gl.glPushAttrib(gl.GL_ENABLE_BIT | gl.GL_CURRENT_BIT) gl.glColor4f(1, 1, 1, 1) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) self.texture.blit(x - self.hot_x, y - self.hot_y, 0) gl.glPopAttrib() def _PlatformEventHandler(data): '''Decorator for platform event handlers. Apply giving the platform-specific data needed by the window to associate the method with an event. See platform-specific subclasses of this decorator for examples. The following attributes are set on the function, which is returned otherwise unchanged: _platform_event True _platform_event_data List of data applied to the function (permitting multiple decorators on the same method). ''' def _event_wrapper(f): f._platform_event = True if not hasattr(f, '_platform_event_data'): f._platform_event_data = [] f._platform_event_data.append(data) return f return _event_wrapper def _ViewEventHandler(f): f._view = True return f class _WindowMetaclass(type): '''Sets the _platform_event_names class variable on the window subclass. ''' def __init__(cls, name, bases, dict): cls._platform_event_names = set() for base in bases: if hasattr(base, '_platform_event_names'): cls._platform_event_names.update(base._platform_event_names) for name, func in dict.items(): if hasattr(func, '_platform_event'): cls._platform_event_names.add(name) super(_WindowMetaclass, cls).__init__(name, bases, dict) class BaseWindow(EventDispatcher): '''Platform-independent application window. A window is a "heavyweight" object occupying operating system resources. The "client" or "content" area of a window is filled entirely with an OpenGL viewport. Applications have no access to operating system widgets or controls; all rendering must be done via OpenGL. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). When floating, windows may appear borderless or decorated with a platform-specific frame (including, for example, the title bar, minimize and close buttons, resize handles, and so on). While it is possible to set the location of a window, it is recommended that applications allow the platform to place it according to local conventions. This will ensure it is not obscured by other windows, and appears on an appropriate screen for the user. To render into a window, you must first call `switch_to`, to make it the current OpenGL context. If you use only one window in the application, there is no need to do this. :Ivariables: `has_exit` : bool True if the user has attempted to close the window. :deprecated: Windows are closed immediately by the default `on_close` handler when `pyglet.app.event_loop` is being used. ''' __metaclass__ = _WindowMetaclass # Filled in by metaclass with the names of all methods on this (sub)class # that are platform event handlers. _platform_event_names = set() #: The default window style. WINDOW_STYLE_DEFAULT = None #: The window style for pop-up dialogs. WINDOW_STYLE_DIALOG = 'dialog' #: The window style for tool windows. WINDOW_STYLE_TOOL = 'tool' #: A window style without any decoration. WINDOW_STYLE_BORDERLESS = 'borderless' #: The default mouse cursor. CURSOR_DEFAULT = None #: A crosshair mouse cursor. CURSOR_CROSSHAIR = 'crosshair' #: A pointing hand mouse cursor. CURSOR_HAND = 'hand' #: A "help" mouse cursor; typically a question mark and an arrow. CURSOR_HELP = 'help' #: A mouse cursor indicating that the selected operation is not permitted. CURSOR_NO = 'no' #: A mouse cursor indicating the element can be resized. CURSOR_SIZE = 'size' #: A mouse cursor indicating the element can be resized from the top #: border. CURSOR_SIZE_UP = 'size_up' #: A mouse cursor indicating the element can be resized from the #: upper-right corner. CURSOR_SIZE_UP_RIGHT = 'size_up_right' #: A mouse cursor indicating the element can be resized from the right #: border. CURSOR_SIZE_RIGHT = 'size_right' #: A mouse cursor indicating the element can be resized from the lower-right #: corner. CURSOR_SIZE_DOWN_RIGHT = 'size_down_right' #: A mouse cursor indicating the element can be resized from the bottom #: border. CURSOR_SIZE_DOWN = 'size_down' #: A mouse cursor indicating the element can be resized from the lower-left #: corner. CURSOR_SIZE_DOWN_LEFT = 'size_down_left' #: A mouse cursor indicating the element can be resized from the left #: border. CURSOR_SIZE_LEFT = 'size_left' #: A mouse cursor indicating the element can be resized from the upper-left #: corner. CURSOR_SIZE_UP_LEFT = 'size_up_left' #: A mouse cursor indicating the element can be resized vertically. CURSOR_SIZE_UP_DOWN = 'size_up_down' #: A mouse cursor indicating the element can be resized horizontally. CURSOR_SIZE_LEFT_RIGHT = 'size_left_right' #: A text input mouse cursor (I-beam). CURSOR_TEXT = 'text' #: A "wait" mouse cursor; typically an hourglass or watch. CURSOR_WAIT = 'wait' #: The "wait" mouse cursor combined with an arrow. CURSOR_WAIT_ARROW = 'wait_arrow' has_exit = False #: Window display contents validity. The `pyglet.app` event loop #: examines every window each iteration and only dispatches the `on_draw` #: event to windows that have `invalid` set. By default, windows always #: have `invalid` set to ``True``. #: #: You can prevent redundant redraws by setting this variable to ``False`` #: in the window's `on_draw` handler, and setting it to True again in #: response to any events that actually do require a window contents #: update. #: #: :type: bool #: :since: pyglet 1.1 invalid = True #: Legacy invalidation flag introduced in pyglet 1.2: set by all event #: dispatches that go to non-empty handlers. The default 1.2 event loop #: will therefore redraw after any handled event or scheduled function. _legacy_invalid = True # Instance variables accessible only via properties _width = None _height = None _caption = None _resizable = False _style = WINDOW_STYLE_DEFAULT _fullscreen = False _visible = False _vsync = False _screen = None _config = None _context = None # Used to restore window size and position after fullscreen _windowed_size = None _windowed_location = None # Subclasses should update these after relevant events _mouse_cursor = DefaultMouseCursor() _mouse_x = 0 _mouse_y = 0 _mouse_visible = True _mouse_exclusive = False _mouse_in_window = False _event_queue = None _enable_event_queue = True # overridden by EventLoop. _allow_dispatch_event = False # controlled by dispatch_events stack frame # Class attributes _default_width = 640 _default_height = 480 def __init__(self, width=None, height=None, caption=None, resizable=False, style=WINDOW_STYLE_DEFAULT, fullscreen=False, visible=True, vsync=True, display=None, screen=None, config=None, context=None, mode=None): '''Create a window. All parameters are optional, and reasonable defaults are assumed where they are not specified. The `display`, `screen`, `config` and `context` parameters form a hierarchy of control: there is no need to specify more than one of these. For example, if you specify `screen` the `display` will be inferred, and a default `config` and `context` will be created. `config` is a special case; it can be a template created by the user specifying the attributes desired, or it can be a complete `config` as returned from `Screen.get_matching_configs` or similar. The context will be active as soon as the window is created, as if `switch_to` was just called. :Parameters: `width` : int Width of the window, in pixels. Defaults to 640, or the screen width if `fullscreen` is True. `height` : int Height of the window, in pixels. Defaults to 480, or the screen height if `fullscreen` is True. `caption` : str or unicode Initial caption (title) of the window. Defaults to ``sys.argv[0]``. `resizable` : bool If True, the window will be resizable. Defaults to False. `style` : int One of the ``WINDOW_STYLE_*`` constants specifying the border style of the window. `fullscreen` : bool If True, the window will cover the entire screen rather than floating. Defaults to False. `visible` : bool Determines if the window is visible immediately after creation. Defaults to True. Set this to False if you would like to change attributes of the window before having it appear to the user. `vsync` : bool If True, buffer flips are synchronised to the primary screen's vertical retrace, eliminating flicker. `display` : `Display` The display device to use. Useful only under X11. `screen` : `Screen` The screen to use, if in fullscreen. `config` : `pyglet.gl.Config` Either a template from which to create a complete config, or a complete config. `context` : `pyglet.gl.Context` The context to attach to this window. The context must not already be attached to another window. `mode` : `ScreenMode` The screen will be switched to this mode if `fullscreen` is True. If None, an appropriate mode is selected to accomodate `width` and `height.` ''' EventDispatcher.__init__(self) self._event_queue = [] if not display: display = get_platform().get_default_display() if not screen: screen = display.get_default_screen() if not config: for template_config in [ gl.Config(double_buffer=True, depth_size=24), gl.Config(double_buffer=True, depth_size=16), None]: try: config = screen.get_best_config(template_config) break except NoSuchConfigException: pass if not config: raise NoSuchConfigException('No standard config is available.') if not config.is_complete(): config = screen.get_best_config(config) if not context: context = config.create_context(gl.current_context) # Set these in reverse order to above, to ensure we get user # preference self._context = context self._config = self._context.config # XXX deprecate config's being screen-specific if hasattr(self._config, 'screen'): self._screen = self._config.screen else: display = self._config.canvas.display self._screen = display.get_default_screen() self._display = self._screen.display if fullscreen: if width is None and height is None: self._windowed_size = self._default_width, self._default_height width, height = self._set_fullscreen_mode(mode, width, height) if not self._windowed_size: self._windowed_size = width, height else: if width is None: width = self._default_width if height is None: height = self._default_height self._width = width self._height = height self._resizable = resizable self._fullscreen = fullscreen self._style = style if pyglet.options['vsync'] is not None: self._vsync = pyglet.options['vsync'] else: self._vsync = vsync if caption is None: caption = sys.argv[0] self._caption = caption from pyglet import app app.windows.add(self) self._create() self.switch_to() if visible: self.set_visible(True) self.activate() def __repr__(self): return '%s(width=%d, height=%d)' % \ (self.__class__.__name__, self.width, self.height) def _create(self): raise NotImplementedError('abstract') def _recreate(self, changes): '''Recreate the window with current attributes. :Parameters: `changes` : list of str List of attribute names that were changed since the last `_create` or `_recreate`. For example, ``['fullscreen']`` is given if the window is to be toggled to or from fullscreen. ''' raise NotImplementedError('abstract') def flip(self): '''Swap the OpenGL front and back buffers. Call this method on a double-buffered window to update the visible display with the back buffer. The contents of the back buffer is undefined after this operation. Windows are double-buffered by default. This method is called automatically by `EventLoop` after the `on_draw` event. ''' raise NotImplementedError('abstract') def switch_to(self): '''Make this window the current OpenGL rendering context. Only one OpenGL context can be active at a time. This method sets the current window's context to be current. You should use this method in preference to `pyglet.gl.Context.set_current`, as it may perform additional initialisation functions. ''' raise NotImplementedError('abstract') def set_fullscreen(self, fullscreen=True, screen=None, mode=None, width=None, height=None): '''Toggle to or from fullscreen. After toggling fullscreen, the GL context should have retained its state and objects, however the buffers will need to be cleared and redrawn. If `width` and `height` are specified and `fullscreen` is True, the screen may be switched to a different resolution that most closely matches the given size. If the resolution doesn't match exactly, a higher resolution is selected and the window will be centered within a black border covering the rest of the screen. :Parameters: `fullscreen` : bool True if the window should be made fullscreen, False if it should be windowed. `screen` : Screen If not None and fullscreen is True, the window is moved to the given screen. The screen must belong to the same display as the window. `mode` : `ScreenMode` The screen will be switched to the given mode. The mode must have been obtained by enumerating `Screen.get_modes`. If None, an appropriate mode will be selected from the given `width` and `height`. `width` : int Optional width of the window. If unspecified, defaults to the previous window size when windowed, or the screen size if fullscreen. **Since:** pyglet 1.2 `height` : int Optional height of the window. If unspecified, defaults to the previous window size when windowed, or the screen size if fullscreen. **Since:** pyglet 1.2 ''' if (fullscreen == self._fullscreen and (screen is None or screen is self._screen) and (width is None or width == self._width) and (height is None or height == self._height)): return if not self._fullscreen: # Save windowed size self._windowed_size = self.get_size() self._windowed_location = self.get_location() if fullscreen and screen is not None: assert screen.display is self.display self._screen = screen self._fullscreen = fullscreen if self._fullscreen: self._width, self._height = self._set_fullscreen_mode( mode, width, height) else: self.screen.restore_mode() self._width, self._height = self._windowed_size if width is not None: self._width = width if height is not None: self._height = height self._recreate(['fullscreen']) if not self._fullscreen and self._windowed_location: # Restore windowed location. # TODO: Move into platform _create? # Not harmless on Carbon because upsets _width and _height # via _on_window_bounds_changed. if pyglet.compat_platform != 'darwin' or pyglet.options['darwin_cocoa']: self.set_location(*self._windowed_location) def _set_fullscreen_mode(self, mode, width, height): if mode is not None: self.screen.set_mode(mode) if width is None: width = self.screen.width if height is None: height = self.screen.height elif width is not None or height is not None: if width is None: width = 0 if height is None: height = 0 mode = self.screen.get_closest_mode(width, height) if mode is not None: self.screen.set_mode(mode) elif self.screen.get_modes(): # Only raise exception if mode switching is at all possible. raise NoSuchScreenModeException( 'No mode matching %dx%d' % (width, height)) else: width = self.screen.width height = self.screen.height return width, height def on_resize(self, width, height): '''A default resize event handler. This default handler updates the GL viewport to cover the entire window and sets the ``GL_PROJECTION`` matrix to be orthogonal in window space. The bottom-left corner is (0, 0) and the top-right corner is the width and height of the window in pixels. Override this event handler with your own to create another projection, for example in perspective. ''' gl.glViewport(0, 0, width, height) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() gl.glOrtho(0, width, 0, height, -1, 1) gl.glMatrixMode(gl.GL_MODELVIEW) def on_close(self): '''Default on_close handler.''' self.has_exit = True from pyglet import app if app.event_loop.is_running: self.close() def on_key_press(self, symbol, modifiers): '''Default on_key_press handler.''' if symbol == key.ESCAPE and not (modifiers & ~(key.MOD_NUMLOCK | key.MOD_CAPSLOCK | key.MOD_SCROLLLOCK)): self.dispatch_event('on_close') def close(self): '''Close the window. After closing the window, the GL context will be invalid. The window instance cannot be reused once closed (see also `set_visible`). The `pyglet.app.EventLoop.on_window_close` event is dispatched on `pyglet.app.event_loop` when this method is called. ''' from pyglet import app if not self._context: return app.windows.remove(self) self._context.destroy() self._config = None self._context = None if app.event_loop: app.event_loop.dispatch_event('on_window_close', self) def draw_mouse_cursor(self): '''Draw the custom mouse cursor. If the current mouse cursor has ``drawable`` set, this method is called before the buffers are flipped to render it. This method always leaves the ``GL_MODELVIEW`` matrix as current, regardless of what it was set to previously. No other GL state is affected. There is little need to override this method; instead, subclass ``MouseCursor`` and provide your own ``draw`` method. ''' # Draw mouse cursor if set and visible. # XXX leaves state in modelview regardless of starting state if (self._mouse_cursor.drawable and self._mouse_visible and self._mouse_in_window): gl.glMatrixMode(gl.GL_PROJECTION) gl.glPushMatrix() gl.glLoadIdentity() gl.glOrtho(0, self.width, 0, self.height, -1, 1) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() gl.glLoadIdentity() self._mouse_cursor.draw(self._mouse_x, self._mouse_y) gl.glMatrixMode(gl.GL_PROJECTION) gl.glPopMatrix() gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPopMatrix() # Properties provide read-only access to instance variables. Use # set_* methods to change them if applicable. caption = property(lambda self: self._caption, doc='''The window caption (title). Read-only. :type: str ''') resizable = property(lambda self: self._resizable, doc='''True if the window is resizable. Read-only. :type: bool ''') style = property(lambda self: self._style, doc='''The window style; one of the ``WINDOW_STYLE_*`` constants. Read-only. :type: int ''') fullscreen = property(lambda self: self._fullscreen, doc='''True if the window is currently fullscreen. Read-only. :type: bool ''') visible = property(lambda self: self._visible, doc='''True if the window is currently visible. Read-only. :type: bool ''') vsync = property(lambda self: self._vsync, doc='''True if buffer flips are synchronised to the screen's vertical retrace. Read-only. :type: bool ''') display = property(lambda self: self._display, doc='''The display this window belongs to. Read-only. :type: `Display` ''') screen = property(lambda self: self._screen, doc='''The screen this window is fullscreen in. Read-only. :type: `Screen` ''') config = property(lambda self: self._config, doc='''A GL config describing the context of this window. Read-only. :type: `pyglet.gl.Config` ''') context = property(lambda self: self._context, doc='''The OpenGL context attached to this window. Read-only. :type: `pyglet.gl.Context` ''') # These are the only properties that can be set width = property(lambda self: self.get_size()[0], lambda self, width: self.set_size(width, self.height), doc='''The width of the window, in pixels. Read-write. :type: int ''') height = property(lambda self: self.get_size()[1], lambda self, height: self.set_size(self.width, height), doc='''The height of the window, in pixels. Read-write. :type: int ''') def set_caption(self, caption): '''Set the window's caption. The caption appears in the titlebar of the window, if it has one, and in the taskbar on Windows and many X11 window managers. :Parameters: `caption` : str or unicode The caption to set. ''' raise NotImplementedError('abstract') def set_minimum_size(self, width, height): '''Set the minimum size of the window. Once set, the user will not be able to resize the window smaller than the given dimensions. There is no way to remove the minimum size constraint on a window (but you could set it to 0,0). The behaviour is undefined if the minimum size is set larger than the current size of the window. The window size does not include the border or title bar. :Parameters: `width` : int Minimum width of the window, in pixels. `height` : int Minimum height of the window, in pixels. ''' raise NotImplementedError('abstract') def set_maximum_size(self, width, height): '''Set the maximum size of the window. Once set, the user will not be able to resize the window larger than the given dimensions. There is no way to remove the maximum size constraint on a window (but you could set it to a large value). The behaviour is undefined if the maximum size is set smaller than the current size of the window. The window size does not include the border or title bar. :Parameters: `width` : int Maximum width of the window, in pixels. `height` : int Maximum height of the window, in pixels. ''' raise NotImplementedError('abstract') def set_size(self, width, height): '''Resize the window. The behaviour is undefined if the window is not resizable, or if it is currently fullscreen. The window size does not include the border or title bar. :Parameters: `width` : int New width of the window, in pixels. `height` : int New height of the window, in pixels. ''' raise NotImplementedError('abstract') def get_size(self): '''Return the current size of the window. The window size does not include the border or title bar. :rtype: (int, int) :return: The width and height of the window, in pixels. ''' raise NotImplementedError('abstract') def set_location(self, x, y): '''Set the position of the window. :Parameters: `x` : int Distance of the left edge of the window from the left edge of the virtual desktop, in pixels. `y` : int Distance of the top edge of the window from the top edge of the virtual desktop, in pixels. ''' raise NotImplementedError('abstract') def get_location(self): '''Return the current position of the window. :rtype: (int, int) :return: The distances of the left and top edges from their respective edges on the virtual desktop, in pixels. ''' raise NotImplementedError('abstract') def activate(self): '''Attempt to restore keyboard focus to the window. Depending on the window manager or operating system, this may not be successful. For example, on Windows XP an application is not allowed to "steal" focus from another application. Instead, the window's taskbar icon will flash, indicating it requires attention. ''' raise NotImplementedError('abstract') def set_visible(self, visible=True): '''Show or hide the window. :Parameters: `visible` : bool If True, the window will be shown; otherwise it will be hidden. ''' raise NotImplementedError('abstract') def minimize(self): '''Minimize the window. ''' raise NotImplementedError('abstract') def maximize(self): '''Maximize the window. The behaviour of this method is somewhat dependent on the user's display setup. On a multi-monitor system, the window may maximize to either a single screen or the entire virtual desktop. ''' raise NotImplementedError('abstract') def set_vsync(self, vsync): '''Enable or disable vertical sync control. When enabled, this option ensures flips from the back to the front buffer are performed only during the vertical retrace period of the primary display. This can prevent "tearing" or flickering when the buffer is updated in the middle of a video scan. Note that LCD monitors have an analogous time in which they are not reading from the video buffer; while it does not correspond to a vertical retrace it has the same effect. With multi-monitor systems the secondary monitor cannot be synchronised to, so tearing and flicker cannot be avoided when the window is positioned outside of the primary display. In this case it may be advisable to forcibly reduce the framerate (for example, using `pyglet.clock.set_fps_limit`). :Parameters: `vsync` : bool If True, vsync is enabled, otherwise it is disabled. ''' raise NotImplementedError('abstract') def set_mouse_visible(self, visible=True): '''Show or hide the mouse cursor. The mouse cursor will only be hidden while it is positioned within this window. Mouse events will still be processed as usual. :Parameters: `visible` : bool If True, the mouse cursor will be visible, otherwise it will be hidden. ''' self._mouse_visible = visible self.set_mouse_platform_visible() def set_mouse_platform_visible(self, platform_visible=None): '''Set the platform-drawn mouse cursor visibility. This is called automatically after changing the mouse cursor or exclusive mode. Applications should not normally need to call this method, see `set_mouse_visible` instead. :Parameters: `platform_visible` : bool or None If None, sets platform visibility to the required visibility for the current exclusive mode and cursor type. Otherwise, a bool value will override and force a visibility. ''' raise NotImplementedError() def set_mouse_cursor(self, cursor=None): '''Change the appearance of the mouse cursor. The appearance of the mouse cursor is only changed while it is within this window. :Parameters: `cursor` : `MouseCursor` The cursor to set, or None to restore the default cursor. ''' if cursor is None: cursor = DefaultMouseCursor() self._mouse_cursor = cursor self.set_mouse_platform_visible() def set_exclusive_mouse(self, exclusive=True): '''Hide the mouse cursor and direct all mouse events to this window. When enabled, this feature prevents the mouse leaving the window. It is useful for certain styles of games that require complete control of the mouse. The position of the mouse as reported in subsequent events is meaningless when exclusive mouse is enabled; you should only use the relative motion parameters ``dx`` and ``dy``. :Parameters: `exclusive` : bool If True, exclusive mouse is enabled, otherwise it is disabled. ''' raise NotImplementedError('abstract') def set_exclusive_keyboard(self, exclusive=True): '''Prevent the user from switching away from this window using keyboard accelerators. When enabled, this feature disables certain operating-system specific key combinations such as Alt+Tab (Command+Tab on OS X). This can be useful in certain kiosk applications, it should be avoided in general applications or games. :Parameters: `exclusive` : bool If True, exclusive keyboard is enabled, otherwise it is disabled. ''' raise NotImplementedError('abstract') def get_system_mouse_cursor(self, name): '''Obtain a system mouse cursor. Use `set_mouse_cursor` to make the cursor returned by this method active. The names accepted by this method are the ``CURSOR_*`` constants defined on this class. :Parameters: `name` : str Name describing the mouse cursor to return. For example, ``CURSOR_WAIT``, ``CURSOR_HELP``, etc. :rtype: `MouseCursor` :return: A mouse cursor which can be used with `set_mouse_cursor`. ''' raise NotImplementedError() def set_icon(self, *images): '''Set the window icon. If multiple images are provided, one with an appropriate size will be selected (if the correct size is not provided, the image will be scaled). Useful sizes to provide are 16x16, 32x32, 64x64 (Mac only) and 128x128 (Mac only). :Parameters: `images` : sequence of `pyglet.image.AbstractImage` List of images to use for the window icon. ''' pass def clear(self): '''Clear the window. This is a convenience method for clearing the color and depth buffer. The window must be the active context (see `switch_to`). ''' gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) def dispatch_event(self, *args): if not self._enable_event_queue or self._allow_dispatch_event: if EventDispatcher.dispatch_event(self, *args) != False: self._legacy_invalid = True else: self._event_queue.append(args) def dispatch_events(self): '''Poll the operating system event queue for new events and call attached event handlers. This method is provided for legacy applications targeting pyglet 1.0, and advanced applications that must integrate their event loop into another framework. Typical applications should use `pyglet.app.run`. ''' raise NotImplementedError('abstract') # If documenting, show the event methods. Otherwise, leave them out # as they are not really methods. if _is_epydoc: def on_key_press(symbol, modifiers): '''A key on the keyboard was pressed (and held down). In pyglet 1.0 the default handler sets `has_exit` to ``True`` if the ``ESC`` key is pressed. In pyglet 1.1 the default handler dispatches the `on_close` event if the ``ESC`` key is pressed. :Parameters: `symbol` : int The key symbol pressed. `modifiers` : int Bitwise combination of the key modifiers active. :event: ''' def on_key_release(symbol, modifiers): '''A key on the keyboard was released. :Parameters: `symbol` : int The key symbol pressed. `modifiers` : int Bitwise combination of the key modifiers active. :event: ''' def on_text(text): '''The user input some text. Typically this is called after `on_key_press` and before `on_key_release`, but may also be called multiple times if the key is held down (key repeating); or called without key presses if another input method was used (e.g., a pen input). You should always use this method for interpreting text, as the key symbols often have complex mappings to their unicode representation which this event takes care of. :Parameters: `text` : unicode The text entered by the user. :event: ''' def on_text_motion(motion): '''The user moved the text input cursor. Typically this is called after `on_key_press` and before `on_key_release`, but may also be called multiple times if the key is help down (key repeating). You should always use this method for moving the text input cursor (caret), as different platforms have different default keyboard mappings, and key repeats are handled correctly. The values that `motion` can take are defined in `pyglet.window.key`: * MOTION_UP * MOTION_RIGHT * MOTION_DOWN * MOTION_LEFT * MOTION_NEXT_WORD * MOTION_PREVIOUS_WORD * MOTION_BEGINNING_OF_LINE * MOTION_END_OF_LINE * MOTION_NEXT_PAGE * MOTION_PREVIOUS_PAGE * MOTION_BEGINNING_OF_FILE * MOTION_END_OF_FILE * MOTION_BACKSPACE * MOTION_DELETE :Parameters: `motion` : int The direction of motion; see remarks. :event: ''' def on_text_motion_select(motion): '''The user moved the text input cursor while extending the selection. Typically this is called after `on_key_press` and before `on_key_release`, but may also be called multiple times if the key is help down (key repeating). You should always use this method for responding to text selection events rather than the raw `on_key_press`, as different platforms have different default keyboard mappings, and key repeats are handled correctly. The values that `motion` can take are defined in `pyglet.window.key`: * MOTION_UP * MOTION_RIGHT * MOTION_DOWN * MOTION_LEFT * MOTION_NEXT_WORD * MOTION_PREVIOUS_WORD * MOTION_BEGINNING_OF_LINE * MOTION_END_OF_LINE * MOTION_NEXT_PAGE * MOTION_PREVIOUS_PAGE * MOTION_BEGINNING_OF_FILE * MOTION_END_OF_FILE :Parameters: `motion` : int The direction of selection motion; see remarks. :event: ''' def on_mouse_motion(x, y, dx, dy): '''The mouse was moved with no buttons held down. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. `dx` : int Relative X position from the previous mouse position. `dy` : int Relative Y position from the previous mouse position. :event: ''' def on_mouse_drag(x, y, dx, dy, buttons, modifiers): '''The mouse was moved with one or more mouse buttons pressed. This event will continue to be fired even if the mouse leaves the window, so long as the drag buttons are continuously held down. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. `dx` : int Relative X position from the previous mouse position. `dy` : int Relative Y position from the previous mouse position. `buttons` : int Bitwise combination of the mouse buttons currently pressed. `modifiers` : int Bitwise combination of any keyboard modifiers currently active. :event: ''' def on_mouse_press(x, y, button, modifiers): '''A mouse button was pressed (and held down). :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. `button` : int The mouse button that was pressed. `modifiers` : int Bitwise combination of any keyboard modifiers currently active. :event: ''' def on_mouse_release(x, y, button, modifiers): '''A mouse button was released. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. `button` : int The mouse button that was released. `modifiers` : int Bitwise combination of any keyboard modifiers currently active. :event: ''' def on_mouse_scroll(x, y, scroll_x, scroll_y): '''The mouse wheel was scrolled. Note that most mice have only a vertical scroll wheel, so `scroll_x` is usually 0. An exception to this is the Apple Mighty Mouse, which has a mouse ball in place of the wheel which allows both `scroll_x` and `scroll_y` movement. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. `scroll_x` : int Number of "clicks" towards the right (left if negative). `scroll_y` : int Number of "clicks" upwards (downwards if negative). :event: ''' def on_close(): '''The user attempted to close the window. This event can be triggered by clicking on the "X" control box in the window title bar, or by some other platform-dependent manner. The default handler sets `has_exit` to ``True``. In pyglet 1.1, if `pyglet.app.event_loop` is being used, `close` is also called, closing the window immediately. :event: ''' def on_mouse_enter(x, y): '''The mouse was moved into the window. This event will not be trigged if the mouse is currently being dragged. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. :event: ''' def on_mouse_leave(x, y): '''The mouse was moved outside of the window. This event will not be trigged if the mouse is currently being dragged. Note that the coordinates of the mouse pointer will be outside of the window rectangle. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. :event: ''' def on_expose(): '''A portion of the window needs to be redrawn. This event is triggered when the window first appears, and any time the contents of the window is invalidated due to another window obscuring it. There is no way to determine which portion of the window needs redrawing. Note that the use of this method is becoming increasingly uncommon, as newer window managers composite windows automatically and keep a backing store of the window contents. :event: ''' def on_resize(width, height): '''The window was resized. The window will have the GL context when this event is dispatched; there is no need to call `switch_to` in this handler. :Parameters: `width` : int The new width of the window, in pixels. `height` : int The new height of the window, in pixels. :event: ''' def on_move(x, y): '''The window was moved. :Parameters: `x` : int Distance from the left edge of the screen to the left edge of the window. `y` : int Distance from the top edge of the screen to the top edge of the window. Note that this is one of few methods in pyglet which use a Y-down coordinate system. :event: ''' def on_activate(): '''The window was activated. This event can be triggered by clicking on the title bar, bringing it to the foreground; or by some platform-specific method. When a window is "active" it has the keyboard focus. :event: ''' def on_deactivate(): '''The window was deactivated. This event can be triggered by clicking on another application window. When a window is deactivated it no longer has the keyboard focus. :event: ''' def on_show(): '''The window was shown. This event is triggered when a window is restored after being minimised, or after being displayed for the first time. :event: ''' def on_hide(): '''The window was hidden. This event is triggered when a window is minimised or (on Mac OS X) hidden by the user. :event: ''' def on_context_lost(): '''The window's GL context was lost. When the context is lost no more GL methods can be called until it is recreated. This is a rare event, triggered perhaps by the user switching to an incompatible video mode. When it occurs, an application will need to reload all objects (display lists, texture objects, shaders) as well as restore the GL state. :event: ''' def on_context_state_lost(): '''The state of the window's GL context was lost. pyglet may sometimes need to recreate the window's GL context if the window is moved to another video device, or between fullscreen or windowed mode. In this case it will try to share the objects (display lists, texture objects, shaders) between the old and new contexts. If this is possible, only the current state of the GL context is lost, and the application should simply restore state. :event: ''' def on_draw(): '''The window contents must be redrawn. The `EventLoop` will dispatch this event when the window should be redrawn. This will happen during idle time after any window events and after any scheduled functions were called. The window will already have the GL context, so there is no need to call `switch_to`. The window's `flip` method will be called after this event, so your event handler should not. You should make no assumptions about the window contents when this event is triggered; a resize or expose event may have invalidated the framebuffer since the last time it was drawn. :since: pyglet 1.1 :event: ''' BaseWindow.register_event_type('on_key_press') BaseWindow.register_event_type('on_key_release') BaseWindow.register_event_type('on_text') BaseWindow.register_event_type('on_text_motion') BaseWindow.register_event_type('on_text_motion_select') BaseWindow.register_event_type('on_mouse_motion') BaseWindow.register_event_type('on_mouse_drag') BaseWindow.register_event_type('on_mouse_press') BaseWindow.register_event_type('on_mouse_release') BaseWindow.register_event_type('on_mouse_scroll') BaseWindow.register_event_type('on_mouse_enter') BaseWindow.register_event_type('on_mouse_leave') BaseWindow.register_event_type('on_close') BaseWindow.register_event_type('on_expose') BaseWindow.register_event_type('on_resize') BaseWindow.register_event_type('on_move') BaseWindow.register_event_type('on_activate') BaseWindow.register_event_type('on_deactivate') BaseWindow.register_event_type('on_show') BaseWindow.register_event_type('on_hide') BaseWindow.register_event_type('on_context_lost') BaseWindow.register_event_type('on_context_state_lost') BaseWindow.register_event_type('on_draw') class FPSDisplay(object): '''Display of a window's framerate. This is a convenience class to aid in profiling and debugging. Typical usage is to create an `FPSDisplay` for each window, and draw the display at the end of the windows' `on_draw` event handler:: window = pyglet.window.Window() fps_display = FPSDisplay(window) @window.event def on_draw(): # ... perform ordinary window drawing operations ... fps_display.draw() The style and position of the display can be modified via the `label` attribute. Different text can be substituted by overriding the `set_fps` method. The display can be set to update more or less often by setting the `update_period` attribute. :Ivariables: `label` : Label The text label displaying the framerate. ''' #: Time in seconds between updates. #: #: :type: float update_period = 0.25 def __init__(self, window): from time import time from pyglet.text import Label self.label = Label('', x=10, y=10, font_size=24, bold=True, color=(127, 127, 127, 127)) self.window = window self._window_flip = window.flip window.flip = self._hook_flip self.time = 0.0 self.last_time = time() self.count = 0 def update(self): '''Records a new data point at the current time. This method is called automatically when the window buffer is flipped. ''' from time import time t = time() self.count += 1 self.time += t - self.last_time self.last_time = t if self.time >= self.update_period: self.set_fps(self.count / self.update_period) self.time %= self.update_period self.count = 0 def set_fps(self, fps): '''Set the label text for the given FPS estimation. Called by `update` every `update_period` seconds. :Parameters: `fps` : float Estimated framerate of the window. ''' self.label.text = '%.2f' % fps def draw(self): '''Draw the label. The OpenGL state is assumed to be at default values, except that the MODELVIEW and PROJECTION matrices are ignored. At the return of this method the matrix mode will be MODELVIEW. ''' gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() gl.glLoadIdentity() gl.glMatrixMode(gl.GL_PROJECTION) gl.glPushMatrix() gl.glLoadIdentity() gl.glOrtho(0, self.window.width, 0, self.window.height, -1, 1) self.label.draw() gl.glPopMatrix() gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPopMatrix() def _hook_flip(self): self.update() self._window_flip() if _is_epydoc: # We are building documentation Window = BaseWindow Window.__name__ = 'Window' del BaseWindow else: # Try to determine which platform to use. if pyglet.compat_platform == 'darwin': if pyglet.options['darwin_cocoa']: from pyglet.window.cocoa import CocoaWindow as Window else: from pyglet.window.carbon import CarbonWindow as Window elif pyglet.compat_platform in ('win32', 'cygwin'): from pyglet.window.win32 import Win32Window as Window else: # XXX HACK around circ problem, should be fixed after removal of # shadow nonsense #pyglet.window = sys.modules[__name__] #import key, mouse from pyglet.window.xlib import XlibWindow as Window # Deprecated API def get_platform(): '''Get an instance of the Platform most appropriate for this system. :deprecated: Use `pyglet.canvas.Display`. :rtype: `Platform` :return: The platform instance. ''' return Platform() class Platform(object): '''Operating-system-level functionality. The platform instance can only be obtained with `get_platform`. Use the platform to obtain a `Display` instance. :deprecated: Use `pyglet.canvas.Display` ''' def get_display(self, name): '''Get a display device by name. This is meaningful only under X11, where the `name` is a string including the host name and display number; for example ``"localhost:1"``. On platforms other than X11, `name` is ignored and the default display is returned. pyglet does not support multiple multiple video devices on Windows or OS X. If more than one device is attached, they will appear as a single virtual device comprising all the attached screens. :deprecated: Use `pyglet.canvas.get_display`. :Parameters: `name` : str The name of the display to connect to. :rtype: `Display` ''' for display in pyglet.app.displays: if display.name == name: return display return pyglet.canvas.Display(name) def get_default_display(self): '''Get the default display device. :deprecated: Use `pyglet.canvas.get_display`. :rtype: `Display` ''' return pyglet.canvas.get_display() if _is_epydoc: class Display(object): '''A display device supporting one or more screens. Use `Platform.get_display` or `Platform.get_default_display` to obtain an instance of this class. Use a display to obtain `Screen` instances. :deprecated: Use `pyglet.canvas.Display`. ''' def __init__(self): raise NotImplementedError('deprecated') def get_screens(self): '''Get the available screens. A typical multi-monitor workstation comprises one `Display` with multiple `Screen` s. This method returns a list of screens which can be enumerated to select one for full-screen display. For the purposes of creating an OpenGL config, the default screen will suffice. :rtype: list of `Screen` ''' raise NotImplementedError('deprecated') def get_default_screen(self): '''Get the default screen as specified by the user's operating system preferences. :rtype: `Screen` ''' raise NotImplementedError('deprecated') def get_windows(self): '''Get the windows currently attached to this display. :rtype: sequence of `Window` ''' raise NotImplementedError('deprecated') else: Display = pyglet.canvas.Display Screen = pyglet.canvas.Screen # XXX remove # Create shadow window. (trickery is for circular import) if not _is_epydoc: pyglet.window = sys.modules[__name__] gl._create_shadow_window()
Python
'''Wrapper for X11 Generated with: tools/genwrappers.py xlib Do not modify this file. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import ctypes from ctypes import * import pyglet.lib _lib = pyglet.lib.load_library('X11') _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)] XlibSpecificationRelease = 6 # /usr/include/X11/Xlib.h:39 X_PROTOCOL = 11 # /usr/include/X11/X.h:53 X_PROTOCOL_REVISION = 0 # /usr/include/X11/X.h:54 XID = c_ulong # /usr/include/X11/X.h:66 Mask = c_ulong # /usr/include/X11/X.h:70 Atom = c_ulong # /usr/include/X11/X.h:74 VisualID = c_ulong # /usr/include/X11/X.h:76 Time = c_ulong # /usr/include/X11/X.h:77 Window = XID # /usr/include/X11/X.h:96 Drawable = XID # /usr/include/X11/X.h:97 Font = XID # /usr/include/X11/X.h:100 Pixmap = XID # /usr/include/X11/X.h:102 Cursor = XID # /usr/include/X11/X.h:103 Colormap = XID # /usr/include/X11/X.h:104 GContext = XID # /usr/include/X11/X.h:105 KeySym = XID # /usr/include/X11/X.h:106 KeyCode = c_ubyte # /usr/include/X11/X.h:108 None_ = 0 # /usr/include/X11/X.h:115 ParentRelative = 1 # /usr/include/X11/X.h:118 CopyFromParent = 0 # /usr/include/X11/X.h:121 PointerWindow = 0 # /usr/include/X11/X.h:126 InputFocus = 1 # /usr/include/X11/X.h:127 PointerRoot = 1 # /usr/include/X11/X.h:129 AnyPropertyType = 0 # /usr/include/X11/X.h:131 AnyKey = 0 # /usr/include/X11/X.h:133 AnyButton = 0 # /usr/include/X11/X.h:135 AllTemporary = 0 # /usr/include/X11/X.h:137 CurrentTime = 0 # /usr/include/X11/X.h:139 NoSymbol = 0 # /usr/include/X11/X.h:141 NoEventMask = 0 # /usr/include/X11/X.h:150 KeyPressMask = 1 # /usr/include/X11/X.h:151 KeyReleaseMask = 2 # /usr/include/X11/X.h:152 ButtonPressMask = 4 # /usr/include/X11/X.h:153 ButtonReleaseMask = 8 # /usr/include/X11/X.h:154 EnterWindowMask = 16 # /usr/include/X11/X.h:155 LeaveWindowMask = 32 # /usr/include/X11/X.h:156 PointerMotionMask = 64 # /usr/include/X11/X.h:157 PointerMotionHintMask = 128 # /usr/include/X11/X.h:158 Button1MotionMask = 256 # /usr/include/X11/X.h:159 Button2MotionMask = 512 # /usr/include/X11/X.h:160 Button3MotionMask = 1024 # /usr/include/X11/X.h:161 Button4MotionMask = 2048 # /usr/include/X11/X.h:162 Button5MotionMask = 4096 # /usr/include/X11/X.h:163 ButtonMotionMask = 8192 # /usr/include/X11/X.h:164 KeymapStateMask = 16384 # /usr/include/X11/X.h:165 ExposureMask = 32768 # /usr/include/X11/X.h:166 VisibilityChangeMask = 65536 # /usr/include/X11/X.h:167 StructureNotifyMask = 131072 # /usr/include/X11/X.h:168 ResizeRedirectMask = 262144 # /usr/include/X11/X.h:169 SubstructureNotifyMask = 524288 # /usr/include/X11/X.h:170 SubstructureRedirectMask = 1048576 # /usr/include/X11/X.h:171 FocusChangeMask = 2097152 # /usr/include/X11/X.h:172 PropertyChangeMask = 4194304 # /usr/include/X11/X.h:173 ColormapChangeMask = 8388608 # /usr/include/X11/X.h:174 OwnerGrabButtonMask = 16777216 # /usr/include/X11/X.h:175 KeyPress = 2 # /usr/include/X11/X.h:181 KeyRelease = 3 # /usr/include/X11/X.h:182 ButtonPress = 4 # /usr/include/X11/X.h:183 ButtonRelease = 5 # /usr/include/X11/X.h:184 MotionNotify = 6 # /usr/include/X11/X.h:185 EnterNotify = 7 # /usr/include/X11/X.h:186 LeaveNotify = 8 # /usr/include/X11/X.h:187 FocusIn = 9 # /usr/include/X11/X.h:188 FocusOut = 10 # /usr/include/X11/X.h:189 KeymapNotify = 11 # /usr/include/X11/X.h:190 Expose = 12 # /usr/include/X11/X.h:191 GraphicsExpose = 13 # /usr/include/X11/X.h:192 NoExpose = 14 # /usr/include/X11/X.h:193 VisibilityNotify = 15 # /usr/include/X11/X.h:194 CreateNotify = 16 # /usr/include/X11/X.h:195 DestroyNotify = 17 # /usr/include/X11/X.h:196 UnmapNotify = 18 # /usr/include/X11/X.h:197 MapNotify = 19 # /usr/include/X11/X.h:198 MapRequest = 20 # /usr/include/X11/X.h:199 ReparentNotify = 21 # /usr/include/X11/X.h:200 ConfigureNotify = 22 # /usr/include/X11/X.h:201 ConfigureRequest = 23 # /usr/include/X11/X.h:202 GravityNotify = 24 # /usr/include/X11/X.h:203 ResizeRequest = 25 # /usr/include/X11/X.h:204 CirculateNotify = 26 # /usr/include/X11/X.h:205 CirculateRequest = 27 # /usr/include/X11/X.h:206 PropertyNotify = 28 # /usr/include/X11/X.h:207 SelectionClear = 29 # /usr/include/X11/X.h:208 SelectionRequest = 30 # /usr/include/X11/X.h:209 SelectionNotify = 31 # /usr/include/X11/X.h:210 ColormapNotify = 32 # /usr/include/X11/X.h:211 ClientMessage = 33 # /usr/include/X11/X.h:212 MappingNotify = 34 # /usr/include/X11/X.h:213 GenericEvent = 35 # /usr/include/X11/X.h:214 LASTEvent = 36 # /usr/include/X11/X.h:215 ShiftMask = 1 # /usr/include/X11/X.h:221 LockMask = 2 # /usr/include/X11/X.h:222 ControlMask = 4 # /usr/include/X11/X.h:223 Mod1Mask = 8 # /usr/include/X11/X.h:224 Mod2Mask = 16 # /usr/include/X11/X.h:225 Mod3Mask = 32 # /usr/include/X11/X.h:226 Mod4Mask = 64 # /usr/include/X11/X.h:227 Mod5Mask = 128 # /usr/include/X11/X.h:228 ShiftMapIndex = 0 # /usr/include/X11/X.h:233 LockMapIndex = 1 # /usr/include/X11/X.h:234 ControlMapIndex = 2 # /usr/include/X11/X.h:235 Mod1MapIndex = 3 # /usr/include/X11/X.h:236 Mod2MapIndex = 4 # /usr/include/X11/X.h:237 Mod3MapIndex = 5 # /usr/include/X11/X.h:238 Mod4MapIndex = 6 # /usr/include/X11/X.h:239 Mod5MapIndex = 7 # /usr/include/X11/X.h:240 Button1Mask = 256 # /usr/include/X11/X.h:246 Button2Mask = 512 # /usr/include/X11/X.h:247 Button3Mask = 1024 # /usr/include/X11/X.h:248 Button4Mask = 2048 # /usr/include/X11/X.h:249 Button5Mask = 4096 # /usr/include/X11/X.h:250 AnyModifier = 32768 # /usr/include/X11/X.h:252 Button1 = 1 # /usr/include/X11/X.h:259 Button2 = 2 # /usr/include/X11/X.h:260 Button3 = 3 # /usr/include/X11/X.h:261 Button4 = 4 # /usr/include/X11/X.h:262 Button5 = 5 # /usr/include/X11/X.h:263 NotifyNormal = 0 # /usr/include/X11/X.h:267 NotifyGrab = 1 # /usr/include/X11/X.h:268 NotifyUngrab = 2 # /usr/include/X11/X.h:269 NotifyWhileGrabbed = 3 # /usr/include/X11/X.h:270 NotifyHint = 1 # /usr/include/X11/X.h:272 NotifyAncestor = 0 # /usr/include/X11/X.h:276 NotifyVirtual = 1 # /usr/include/X11/X.h:277 NotifyInferior = 2 # /usr/include/X11/X.h:278 NotifyNonlinear = 3 # /usr/include/X11/X.h:279 NotifyNonlinearVirtual = 4 # /usr/include/X11/X.h:280 NotifyPointer = 5 # /usr/include/X11/X.h:281 NotifyPointerRoot = 6 # /usr/include/X11/X.h:282 NotifyDetailNone = 7 # /usr/include/X11/X.h:283 VisibilityUnobscured = 0 # /usr/include/X11/X.h:287 VisibilityPartiallyObscured = 1 # /usr/include/X11/X.h:288 VisibilityFullyObscured = 2 # /usr/include/X11/X.h:289 PlaceOnTop = 0 # /usr/include/X11/X.h:293 PlaceOnBottom = 1 # /usr/include/X11/X.h:294 FamilyInternet = 0 # /usr/include/X11/X.h:298 FamilyDECnet = 1 # /usr/include/X11/X.h:299 FamilyChaos = 2 # /usr/include/X11/X.h:300 FamilyInternet6 = 6 # /usr/include/X11/X.h:301 FamilyServerInterpreted = 5 # /usr/include/X11/X.h:304 PropertyNewValue = 0 # /usr/include/X11/X.h:308 PropertyDelete = 1 # /usr/include/X11/X.h:309 ColormapUninstalled = 0 # /usr/include/X11/X.h:313 ColormapInstalled = 1 # /usr/include/X11/X.h:314 GrabModeSync = 0 # /usr/include/X11/X.h:318 GrabModeAsync = 1 # /usr/include/X11/X.h:319 GrabSuccess = 0 # /usr/include/X11/X.h:323 AlreadyGrabbed = 1 # /usr/include/X11/X.h:324 GrabInvalidTime = 2 # /usr/include/X11/X.h:325 GrabNotViewable = 3 # /usr/include/X11/X.h:326 GrabFrozen = 4 # /usr/include/X11/X.h:327 AsyncPointer = 0 # /usr/include/X11/X.h:331 SyncPointer = 1 # /usr/include/X11/X.h:332 ReplayPointer = 2 # /usr/include/X11/X.h:333 AsyncKeyboard = 3 # /usr/include/X11/X.h:334 SyncKeyboard = 4 # /usr/include/X11/X.h:335 ReplayKeyboard = 5 # /usr/include/X11/X.h:336 AsyncBoth = 6 # /usr/include/X11/X.h:337 SyncBoth = 7 # /usr/include/X11/X.h:338 RevertToParent = 2 # /usr/include/X11/X.h:344 Success = 0 # /usr/include/X11/X.h:350 BadRequest = 1 # /usr/include/X11/X.h:351 BadValue = 2 # /usr/include/X11/X.h:352 BadWindow = 3 # /usr/include/X11/X.h:353 BadPixmap = 4 # /usr/include/X11/X.h:354 BadAtom = 5 # /usr/include/X11/X.h:355 BadCursor = 6 # /usr/include/X11/X.h:356 BadFont = 7 # /usr/include/X11/X.h:357 BadMatch = 8 # /usr/include/X11/X.h:358 BadDrawable = 9 # /usr/include/X11/X.h:359 BadAccess = 10 # /usr/include/X11/X.h:360 BadAlloc = 11 # /usr/include/X11/X.h:369 BadColor = 12 # /usr/include/X11/X.h:370 BadGC = 13 # /usr/include/X11/X.h:371 BadIDChoice = 14 # /usr/include/X11/X.h:372 BadName = 15 # /usr/include/X11/X.h:373 BadLength = 16 # /usr/include/X11/X.h:374 BadImplementation = 17 # /usr/include/X11/X.h:375 FirstExtensionError = 128 # /usr/include/X11/X.h:377 LastExtensionError = 255 # /usr/include/X11/X.h:378 InputOutput = 1 # /usr/include/X11/X.h:387 InputOnly = 2 # /usr/include/X11/X.h:388 CWBackPixmap = 1 # /usr/include/X11/X.h:392 CWBackPixel = 2 # /usr/include/X11/X.h:393 CWBorderPixmap = 4 # /usr/include/X11/X.h:394 CWBorderPixel = 8 # /usr/include/X11/X.h:395 CWBitGravity = 16 # /usr/include/X11/X.h:396 CWWinGravity = 32 # /usr/include/X11/X.h:397 CWBackingStore = 64 # /usr/include/X11/X.h:398 CWBackingPlanes = 128 # /usr/include/X11/X.h:399 CWBackingPixel = 256 # /usr/include/X11/X.h:400 CWOverrideRedirect = 512 # /usr/include/X11/X.h:401 CWSaveUnder = 1024 # /usr/include/X11/X.h:402 CWEventMask = 2048 # /usr/include/X11/X.h:403 CWDontPropagate = 4096 # /usr/include/X11/X.h:404 CWColormap = 8192 # /usr/include/X11/X.h:405 CWCursor = 16384 # /usr/include/X11/X.h:406 CWX = 1 # /usr/include/X11/X.h:410 CWY = 2 # /usr/include/X11/X.h:411 CWWidth = 4 # /usr/include/X11/X.h:412 CWHeight = 8 # /usr/include/X11/X.h:413 CWBorderWidth = 16 # /usr/include/X11/X.h:414 CWSibling = 32 # /usr/include/X11/X.h:415 CWStackMode = 64 # /usr/include/X11/X.h:416 ForgetGravity = 0 # /usr/include/X11/X.h:421 NorthWestGravity = 1 # /usr/include/X11/X.h:422 NorthGravity = 2 # /usr/include/X11/X.h:423 NorthEastGravity = 3 # /usr/include/X11/X.h:424 WestGravity = 4 # /usr/include/X11/X.h:425 CenterGravity = 5 # /usr/include/X11/X.h:426 EastGravity = 6 # /usr/include/X11/X.h:427 SouthWestGravity = 7 # /usr/include/X11/X.h:428 SouthGravity = 8 # /usr/include/X11/X.h:429 SouthEastGravity = 9 # /usr/include/X11/X.h:430 StaticGravity = 10 # /usr/include/X11/X.h:431 UnmapGravity = 0 # /usr/include/X11/X.h:435 NotUseful = 0 # /usr/include/X11/X.h:439 WhenMapped = 1 # /usr/include/X11/X.h:440 Always = 2 # /usr/include/X11/X.h:441 IsUnmapped = 0 # /usr/include/X11/X.h:445 IsUnviewable = 1 # /usr/include/X11/X.h:446 IsViewable = 2 # /usr/include/X11/X.h:447 SetModeInsert = 0 # /usr/include/X11/X.h:451 SetModeDelete = 1 # /usr/include/X11/X.h:452 DestroyAll = 0 # /usr/include/X11/X.h:456 RetainPermanent = 1 # /usr/include/X11/X.h:457 RetainTemporary = 2 # /usr/include/X11/X.h:458 Above = 0 # /usr/include/X11/X.h:462 Below = 1 # /usr/include/X11/X.h:463 TopIf = 2 # /usr/include/X11/X.h:464 BottomIf = 3 # /usr/include/X11/X.h:465 Opposite = 4 # /usr/include/X11/X.h:466 RaiseLowest = 0 # /usr/include/X11/X.h:470 LowerHighest = 1 # /usr/include/X11/X.h:471 PropModeReplace = 0 # /usr/include/X11/X.h:475 PropModePrepend = 1 # /usr/include/X11/X.h:476 PropModeAppend = 2 # /usr/include/X11/X.h:477 GXclear = 0 # /usr/include/X11/X.h:485 GXand = 1 # /usr/include/X11/X.h:486 GXandReverse = 2 # /usr/include/X11/X.h:487 GXcopy = 3 # /usr/include/X11/X.h:488 GXandInverted = 4 # /usr/include/X11/X.h:489 GXnoop = 5 # /usr/include/X11/X.h:490 GXxor = 6 # /usr/include/X11/X.h:491 GXor = 7 # /usr/include/X11/X.h:492 GXnor = 8 # /usr/include/X11/X.h:493 GXequiv = 9 # /usr/include/X11/X.h:494 GXinvert = 10 # /usr/include/X11/X.h:495 GXorReverse = 11 # /usr/include/X11/X.h:496 GXcopyInverted = 12 # /usr/include/X11/X.h:497 GXorInverted = 13 # /usr/include/X11/X.h:498 GXnand = 14 # /usr/include/X11/X.h:499 GXset = 15 # /usr/include/X11/X.h:500 LineSolid = 0 # /usr/include/X11/X.h:504 LineOnOffDash = 1 # /usr/include/X11/X.h:505 LineDoubleDash = 2 # /usr/include/X11/X.h:506 CapNotLast = 0 # /usr/include/X11/X.h:510 CapButt = 1 # /usr/include/X11/X.h:511 CapRound = 2 # /usr/include/X11/X.h:512 CapProjecting = 3 # /usr/include/X11/X.h:513 JoinMiter = 0 # /usr/include/X11/X.h:517 JoinRound = 1 # /usr/include/X11/X.h:518 JoinBevel = 2 # /usr/include/X11/X.h:519 FillSolid = 0 # /usr/include/X11/X.h:523 FillTiled = 1 # /usr/include/X11/X.h:524 FillStippled = 2 # /usr/include/X11/X.h:525 FillOpaqueStippled = 3 # /usr/include/X11/X.h:526 EvenOddRule = 0 # /usr/include/X11/X.h:530 WindingRule = 1 # /usr/include/X11/X.h:531 ClipByChildren = 0 # /usr/include/X11/X.h:535 IncludeInferiors = 1 # /usr/include/X11/X.h:536 Unsorted = 0 # /usr/include/X11/X.h:540 YSorted = 1 # /usr/include/X11/X.h:541 YXSorted = 2 # /usr/include/X11/X.h:542 YXBanded = 3 # /usr/include/X11/X.h:543 CoordModeOrigin = 0 # /usr/include/X11/X.h:547 CoordModePrevious = 1 # /usr/include/X11/X.h:548 Complex = 0 # /usr/include/X11/X.h:552 Nonconvex = 1 # /usr/include/X11/X.h:553 Convex = 2 # /usr/include/X11/X.h:554 ArcChord = 0 # /usr/include/X11/X.h:558 ArcPieSlice = 1 # /usr/include/X11/X.h:559 GCFunction = 1 # /usr/include/X11/X.h:564 GCPlaneMask = 2 # /usr/include/X11/X.h:565 GCForeground = 4 # /usr/include/X11/X.h:566 GCBackground = 8 # /usr/include/X11/X.h:567 GCLineWidth = 16 # /usr/include/X11/X.h:568 GCLineStyle = 32 # /usr/include/X11/X.h:569 GCCapStyle = 64 # /usr/include/X11/X.h:570 GCJoinStyle = 128 # /usr/include/X11/X.h:571 GCFillStyle = 256 # /usr/include/X11/X.h:572 GCFillRule = 512 # /usr/include/X11/X.h:573 GCTile = 1024 # /usr/include/X11/X.h:574 GCStipple = 2048 # /usr/include/X11/X.h:575 GCTileStipXOrigin = 4096 # /usr/include/X11/X.h:576 GCTileStipYOrigin = 8192 # /usr/include/X11/X.h:577 GCFont = 16384 # /usr/include/X11/X.h:578 GCSubwindowMode = 32768 # /usr/include/X11/X.h:579 GCGraphicsExposures = 65536 # /usr/include/X11/X.h:580 GCClipXOrigin = 131072 # /usr/include/X11/X.h:581 GCClipYOrigin = 262144 # /usr/include/X11/X.h:582 GCClipMask = 524288 # /usr/include/X11/X.h:583 GCDashOffset = 1048576 # /usr/include/X11/X.h:584 GCDashList = 2097152 # /usr/include/X11/X.h:585 GCArcMode = 4194304 # /usr/include/X11/X.h:586 GCLastBit = 22 # /usr/include/X11/X.h:588 FontLeftToRight = 0 # /usr/include/X11/X.h:595 FontRightToLeft = 1 # /usr/include/X11/X.h:596 FontChange = 255 # /usr/include/X11/X.h:598 XYBitmap = 0 # /usr/include/X11/X.h:606 XYPixmap = 1 # /usr/include/X11/X.h:607 ZPixmap = 2 # /usr/include/X11/X.h:608 AllocNone = 0 # /usr/include/X11/X.h:616 AllocAll = 1 # /usr/include/X11/X.h:617 DoRed = 1 # /usr/include/X11/X.h:622 DoGreen = 2 # /usr/include/X11/X.h:623 DoBlue = 4 # /usr/include/X11/X.h:624 CursorShape = 0 # /usr/include/X11/X.h:632 TileShape = 1 # /usr/include/X11/X.h:633 StippleShape = 2 # /usr/include/X11/X.h:634 AutoRepeatModeOff = 0 # /usr/include/X11/X.h:640 AutoRepeatModeOn = 1 # /usr/include/X11/X.h:641 AutoRepeatModeDefault = 2 # /usr/include/X11/X.h:642 LedModeOff = 0 # /usr/include/X11/X.h:644 LedModeOn = 1 # /usr/include/X11/X.h:645 KBKeyClickPercent = 1 # /usr/include/X11/X.h:649 KBBellPercent = 2 # /usr/include/X11/X.h:650 KBBellPitch = 4 # /usr/include/X11/X.h:651 KBBellDuration = 8 # /usr/include/X11/X.h:652 KBLed = 16 # /usr/include/X11/X.h:653 KBLedMode = 32 # /usr/include/X11/X.h:654 KBKey = 64 # /usr/include/X11/X.h:655 KBAutoRepeatMode = 128 # /usr/include/X11/X.h:656 MappingSuccess = 0 # /usr/include/X11/X.h:658 MappingBusy = 1 # /usr/include/X11/X.h:659 MappingFailed = 2 # /usr/include/X11/X.h:660 MappingModifier = 0 # /usr/include/X11/X.h:662 MappingKeyboard = 1 # /usr/include/X11/X.h:663 MappingPointer = 2 # /usr/include/X11/X.h:664 DontPreferBlanking = 0 # /usr/include/X11/X.h:670 PreferBlanking = 1 # /usr/include/X11/X.h:671 DefaultBlanking = 2 # /usr/include/X11/X.h:672 DisableScreenSaver = 0 # /usr/include/X11/X.h:674 DisableScreenInterval = 0 # /usr/include/X11/X.h:675 DontAllowExposures = 0 # /usr/include/X11/X.h:677 AllowExposures = 1 # /usr/include/X11/X.h:678 DefaultExposures = 2 # /usr/include/X11/X.h:679 ScreenSaverReset = 0 # /usr/include/X11/X.h:683 ScreenSaverActive = 1 # /usr/include/X11/X.h:684 HostInsert = 0 # /usr/include/X11/X.h:692 HostDelete = 1 # /usr/include/X11/X.h:693 EnableAccess = 1 # /usr/include/X11/X.h:697 DisableAccess = 0 # /usr/include/X11/X.h:698 StaticGray = 0 # /usr/include/X11/X.h:704 GrayScale = 1 # /usr/include/X11/X.h:705 StaticColor = 2 # /usr/include/X11/X.h:706 PseudoColor = 3 # /usr/include/X11/X.h:707 TrueColor = 4 # /usr/include/X11/X.h:708 DirectColor = 5 # /usr/include/X11/X.h:709 LSBFirst = 0 # /usr/include/X11/X.h:714 MSBFirst = 1 # /usr/include/X11/X.h:715 # /usr/include/X11/Xlib.h:73 _Xmblen = _lib._Xmblen _Xmblen.restype = c_int _Xmblen.argtypes = [c_char_p, c_int] X_HAVE_UTF8_STRING = 1 # /usr/include/X11/Xlib.h:85 XPointer = c_char_p # /usr/include/X11/Xlib.h:87 Bool = c_int # /usr/include/X11/Xlib.h:89 Status = c_int # /usr/include/X11/Xlib.h:90 True_ = 1 # /usr/include/X11/Xlib.h:91 False_ = 0 # /usr/include/X11/Xlib.h:92 QueuedAlready = 0 # /usr/include/X11/Xlib.h:94 QueuedAfterReading = 1 # /usr/include/X11/Xlib.h:95 QueuedAfterFlush = 2 # /usr/include/X11/Xlib.h:96 class struct__XExtData(Structure): __slots__ = [ 'number', 'next', 'free_private', 'private_data', ] struct__XExtData._fields_ = [ ('number', c_int), ('next', POINTER(struct__XExtData)), ('free_private', POINTER(CFUNCTYPE(c_int, POINTER(struct__XExtData)))), ('private_data', XPointer), ] XExtData = struct__XExtData # /usr/include/X11/Xlib.h:166 class struct_anon_15(Structure): __slots__ = [ 'extension', 'major_opcode', 'first_event', 'first_error', ] struct_anon_15._fields_ = [ ('extension', c_int), ('major_opcode', c_int), ('first_event', c_int), ('first_error', c_int), ] XExtCodes = struct_anon_15 # /usr/include/X11/Xlib.h:176 class struct_anon_16(Structure): __slots__ = [ 'depth', 'bits_per_pixel', 'scanline_pad', ] struct_anon_16._fields_ = [ ('depth', c_int), ('bits_per_pixel', c_int), ('scanline_pad', c_int), ] XPixmapFormatValues = struct_anon_16 # /usr/include/X11/Xlib.h:186 class struct_anon_17(Structure): __slots__ = [ 'function', 'plane_mask', 'foreground', 'background', 'line_width', 'line_style', 'cap_style', 'join_style', 'fill_style', 'fill_rule', 'arc_mode', 'tile', 'stipple', 'ts_x_origin', 'ts_y_origin', 'font', 'subwindow_mode', 'graphics_exposures', 'clip_x_origin', 'clip_y_origin', 'clip_mask', 'dash_offset', 'dashes', ] struct_anon_17._fields_ = [ ('function', c_int), ('plane_mask', c_ulong), ('foreground', c_ulong), ('background', c_ulong), ('line_width', c_int), ('line_style', c_int), ('cap_style', c_int), ('join_style', c_int), ('fill_style', c_int), ('fill_rule', c_int), ('arc_mode', c_int), ('tile', Pixmap), ('stipple', Pixmap), ('ts_x_origin', c_int), ('ts_y_origin', c_int), ('font', Font), ('subwindow_mode', c_int), ('graphics_exposures', c_int), ('clip_x_origin', c_int), ('clip_y_origin', c_int), ('clip_mask', Pixmap), ('dash_offset', c_int), ('dashes', c_char), ] XGCValues = struct_anon_17 # /usr/include/X11/Xlib.h:218 class struct__XGC(Structure): __slots__ = [ ] struct__XGC._fields_ = [ ('_opaque_struct', c_int) ] class struct__XGC(Structure): __slots__ = [ ] struct__XGC._fields_ = [ ('_opaque_struct', c_int) ] GC = POINTER(struct__XGC) # /usr/include/X11/Xlib.h:233 class struct_anon_18(Structure): __slots__ = [ 'ext_data', 'visualid', 'class', 'red_mask', 'green_mask', 'blue_mask', 'bits_per_rgb', 'map_entries', ] struct_anon_18._fields_ = [ ('ext_data', POINTER(XExtData)), ('visualid', VisualID), ('class', c_int), ('red_mask', c_ulong), ('green_mask', c_ulong), ('blue_mask', c_ulong), ('bits_per_rgb', c_int), ('map_entries', c_int), ] Visual = struct_anon_18 # /usr/include/X11/Xlib.h:249 class struct_anon_19(Structure): __slots__ = [ 'depth', 'nvisuals', 'visuals', ] struct_anon_19._fields_ = [ ('depth', c_int), ('nvisuals', c_int), ('visuals', POINTER(Visual)), ] Depth = struct_anon_19 # /usr/include/X11/Xlib.h:258 class struct_anon_20(Structure): __slots__ = [ 'ext_data', 'display', 'root', 'width', 'height', 'mwidth', 'mheight', 'ndepths', 'depths', 'root_depth', 'root_visual', 'default_gc', 'cmap', 'white_pixel', 'black_pixel', 'max_maps', 'min_maps', 'backing_store', 'save_unders', 'root_input_mask', ] class struct__XDisplay(Structure): __slots__ = [ ] struct__XDisplay._fields_ = [ ('_opaque_struct', c_int) ] struct_anon_20._fields_ = [ ('ext_data', POINTER(XExtData)), ('display', POINTER(struct__XDisplay)), ('root', Window), ('width', c_int), ('height', c_int), ('mwidth', c_int), ('mheight', c_int), ('ndepths', c_int), ('depths', POINTER(Depth)), ('root_depth', c_int), ('root_visual', POINTER(Visual)), ('default_gc', GC), ('cmap', Colormap), ('white_pixel', c_ulong), ('black_pixel', c_ulong), ('max_maps', c_int), ('min_maps', c_int), ('backing_store', c_int), ('save_unders', c_int), ('root_input_mask', c_long), ] Screen = struct_anon_20 # /usr/include/X11/Xlib.h:286 class struct_anon_21(Structure): __slots__ = [ 'ext_data', 'depth', 'bits_per_pixel', 'scanline_pad', ] struct_anon_21._fields_ = [ ('ext_data', POINTER(XExtData)), ('depth', c_int), ('bits_per_pixel', c_int), ('scanline_pad', c_int), ] ScreenFormat = struct_anon_21 # /usr/include/X11/Xlib.h:296 class struct_anon_22(Structure): __slots__ = [ 'background_pixmap', 'background_pixel', 'border_pixmap', 'border_pixel', 'bit_gravity', 'win_gravity', 'backing_store', 'backing_planes', 'backing_pixel', 'save_under', 'event_mask', 'do_not_propagate_mask', 'override_redirect', 'colormap', 'cursor', ] struct_anon_22._fields_ = [ ('background_pixmap', Pixmap), ('background_pixel', c_ulong), ('border_pixmap', Pixmap), ('border_pixel', c_ulong), ('bit_gravity', c_int), ('win_gravity', c_int), ('backing_store', c_int), ('backing_planes', c_ulong), ('backing_pixel', c_ulong), ('save_under', c_int), ('event_mask', c_long), ('do_not_propagate_mask', c_long), ('override_redirect', c_int), ('colormap', Colormap), ('cursor', Cursor), ] XSetWindowAttributes = struct_anon_22 # /usr/include/X11/Xlib.h:317 class struct_anon_23(Structure): __slots__ = [ 'x', 'y', 'width', 'height', 'border_width', 'depth', 'visual', 'root', 'class', 'bit_gravity', 'win_gravity', 'backing_store', 'backing_planes', 'backing_pixel', 'save_under', 'colormap', 'map_installed', 'map_state', 'all_event_masks', 'your_event_mask', 'do_not_propagate_mask', 'override_redirect', 'screen', ] struct_anon_23._fields_ = [ ('x', c_int), ('y', c_int), ('width', c_int), ('height', c_int), ('border_width', c_int), ('depth', c_int), ('visual', POINTER(Visual)), ('root', Window), ('class', c_int), ('bit_gravity', c_int), ('win_gravity', c_int), ('backing_store', c_int), ('backing_planes', c_ulong), ('backing_pixel', c_ulong), ('save_under', c_int), ('colormap', Colormap), ('map_installed', c_int), ('map_state', c_int), ('all_event_masks', c_long), ('your_event_mask', c_long), ('do_not_propagate_mask', c_long), ('override_redirect', c_int), ('screen', POINTER(Screen)), ] XWindowAttributes = struct_anon_23 # /usr/include/X11/Xlib.h:345 class struct_anon_24(Structure): __slots__ = [ 'family', 'length', 'address', ] struct_anon_24._fields_ = [ ('family', c_int), ('length', c_int), ('address', c_char_p), ] XHostAddress = struct_anon_24 # /usr/include/X11/Xlib.h:356 class struct_anon_25(Structure): __slots__ = [ 'typelength', 'valuelength', 'type', 'value', ] struct_anon_25._fields_ = [ ('typelength', c_int), ('valuelength', c_int), ('type', c_char_p), ('value', c_char_p), ] XServerInterpretedAddress = struct_anon_25 # /usr/include/X11/Xlib.h:366 class struct__XImage(Structure): __slots__ = [ 'width', 'height', 'xoffset', 'format', 'data', 'byte_order', 'bitmap_unit', 'bitmap_bit_order', 'bitmap_pad', 'depth', 'bytes_per_line', 'bits_per_pixel', 'red_mask', 'green_mask', 'blue_mask', 'obdata', 'f', ] class struct_funcs(Structure): __slots__ = [ 'create_image', 'destroy_image', 'get_pixel', 'put_pixel', 'sub_image', 'add_pixel', ] class struct__XDisplay(Structure): __slots__ = [ ] struct__XDisplay._fields_ = [ ('_opaque_struct', c_int) ] struct_funcs._fields_ = [ ('create_image', POINTER(CFUNCTYPE(POINTER(struct__XImage), POINTER(struct__XDisplay), POINTER(Visual), c_uint, c_int, c_int, c_char_p, c_uint, c_uint, c_int, c_int))), ('destroy_image', POINTER(CFUNCTYPE(c_int, POINTER(struct__XImage)))), ('get_pixel', POINTER(CFUNCTYPE(c_ulong, POINTER(struct__XImage), c_int, c_int))), ('put_pixel', POINTER(CFUNCTYPE(c_int, POINTER(struct__XImage), c_int, c_int, c_ulong))), ('sub_image', POINTER(CFUNCTYPE(POINTER(struct__XImage), POINTER(struct__XImage), c_int, c_int, c_uint, c_uint))), ('add_pixel', POINTER(CFUNCTYPE(c_int, POINTER(struct__XImage), c_long))), ] struct__XImage._fields_ = [ ('width', c_int), ('height', c_int), ('xoffset', c_int), ('format', c_int), ('data', c_char_p), ('byte_order', c_int), ('bitmap_unit', c_int), ('bitmap_bit_order', c_int), ('bitmap_pad', c_int), ('depth', c_int), ('bytes_per_line', c_int), ('bits_per_pixel', c_int), ('red_mask', c_ulong), ('green_mask', c_ulong), ('blue_mask', c_ulong), ('obdata', XPointer), ('f', struct_funcs), ] XImage = struct__XImage # /usr/include/X11/Xlib.h:405 class struct_anon_26(Structure): __slots__ = [ 'x', 'y', 'width', 'height', 'border_width', 'sibling', 'stack_mode', ] struct_anon_26._fields_ = [ ('x', c_int), ('y', c_int), ('width', c_int), ('height', c_int), ('border_width', c_int), ('sibling', Window), ('stack_mode', c_int), ] XWindowChanges = struct_anon_26 # /usr/include/X11/Xlib.h:416 class struct_anon_27(Structure): __slots__ = [ 'pixel', 'red', 'green', 'blue', 'flags', 'pad', ] struct_anon_27._fields_ = [ ('pixel', c_ulong), ('red', c_ushort), ('green', c_ushort), ('blue', c_ushort), ('flags', c_char), ('pad', c_char), ] XColor = struct_anon_27 # /usr/include/X11/Xlib.h:426 class struct_anon_28(Structure): __slots__ = [ 'x1', 'y1', 'x2', 'y2', ] struct_anon_28._fields_ = [ ('x1', c_short), ('y1', c_short), ('x2', c_short), ('y2', c_short), ] XSegment = struct_anon_28 # /usr/include/X11/Xlib.h:435 class struct_anon_29(Structure): __slots__ = [ 'x', 'y', ] struct_anon_29._fields_ = [ ('x', c_short), ('y', c_short), ] XPoint = struct_anon_29 # /usr/include/X11/Xlib.h:439 class struct_anon_30(Structure): __slots__ = [ 'x', 'y', 'width', 'height', ] struct_anon_30._fields_ = [ ('x', c_short), ('y', c_short), ('width', c_ushort), ('height', c_ushort), ] XRectangle = struct_anon_30 # /usr/include/X11/Xlib.h:444 class struct_anon_31(Structure): __slots__ = [ 'x', 'y', 'width', 'height', 'angle1', 'angle2', ] struct_anon_31._fields_ = [ ('x', c_short), ('y', c_short), ('width', c_ushort), ('height', c_ushort), ('angle1', c_short), ('angle2', c_short), ] XArc = struct_anon_31 # /usr/include/X11/Xlib.h:450 class struct_anon_32(Structure): __slots__ = [ 'key_click_percent', 'bell_percent', 'bell_pitch', 'bell_duration', 'led', 'led_mode', 'key', 'auto_repeat_mode', ] struct_anon_32._fields_ = [ ('key_click_percent', c_int), ('bell_percent', c_int), ('bell_pitch', c_int), ('bell_duration', c_int), ('led', c_int), ('led_mode', c_int), ('key', c_int), ('auto_repeat_mode', c_int), ] XKeyboardControl = struct_anon_32 # /usr/include/X11/Xlib.h:464 class struct_anon_33(Structure): __slots__ = [ 'key_click_percent', 'bell_percent', 'bell_pitch', 'bell_duration', 'led_mask', 'global_auto_repeat', 'auto_repeats', ] struct_anon_33._fields_ = [ ('key_click_percent', c_int), ('bell_percent', c_int), ('bell_pitch', c_uint), ('bell_duration', c_uint), ('led_mask', c_ulong), ('global_auto_repeat', c_int), ('auto_repeats', c_char * 32), ] XKeyboardState = struct_anon_33 # /usr/include/X11/Xlib.h:475 class struct_anon_34(Structure): __slots__ = [ 'time', 'x', 'y', ] struct_anon_34._fields_ = [ ('time', Time), ('x', c_short), ('y', c_short), ] XTimeCoord = struct_anon_34 # /usr/include/X11/Xlib.h:482 class struct_anon_35(Structure): __slots__ = [ 'max_keypermod', 'modifiermap', ] struct_anon_35._fields_ = [ ('max_keypermod', c_int), ('modifiermap', POINTER(KeyCode)), ] XModifierKeymap = struct_anon_35 # /usr/include/X11/Xlib.h:489 class struct__XDisplay(Structure): __slots__ = [ ] struct__XDisplay._fields_ = [ ('_opaque_struct', c_int) ] class struct__XDisplay(Structure): __slots__ = [ ] struct__XDisplay._fields_ = [ ('_opaque_struct', c_int) ] Display = struct__XDisplay # /usr/include/X11/Xlib.h:498 class struct_anon_36(Structure): __slots__ = [ 'ext_data', 'private1', 'fd', 'private2', 'proto_major_version', 'proto_minor_version', 'vendor', 'private3', 'private4', 'private5', 'private6', 'resource_alloc', 'byte_order', 'bitmap_unit', 'bitmap_pad', 'bitmap_bit_order', 'nformats', 'pixmap_format', 'private8', 'release', 'private9', 'private10', 'qlen', 'last_request_read', 'request', 'private11', 'private12', 'private13', 'private14', 'max_request_size', 'db', 'private15', 'display_name', 'default_screen', 'nscreens', 'screens', 'motion_buffer', 'private16', 'min_keycode', 'max_keycode', 'private17', 'private18', 'private19', 'xdefaults', ] class struct__XPrivate(Structure): __slots__ = [ ] struct__XPrivate._fields_ = [ ('_opaque_struct', c_int) ] class struct__XDisplay(Structure): __slots__ = [ ] struct__XDisplay._fields_ = [ ('_opaque_struct', c_int) ] class struct__XPrivate(Structure): __slots__ = [ ] struct__XPrivate._fields_ = [ ('_opaque_struct', c_int) ] class struct__XPrivate(Structure): __slots__ = [ ] struct__XPrivate._fields_ = [ ('_opaque_struct', c_int) ] class struct__XrmHashBucketRec(Structure): __slots__ = [ ] struct__XrmHashBucketRec._fields_ = [ ('_opaque_struct', c_int) ] class struct__XDisplay(Structure): __slots__ = [ ] struct__XDisplay._fields_ = [ ('_opaque_struct', c_int) ] struct_anon_36._fields_ = [ ('ext_data', POINTER(XExtData)), ('private1', POINTER(struct__XPrivate)), ('fd', c_int), ('private2', c_int), ('proto_major_version', c_int), ('proto_minor_version', c_int), ('vendor', c_char_p), ('private3', XID), ('private4', XID), ('private5', XID), ('private6', c_int), ('resource_alloc', POINTER(CFUNCTYPE(XID, POINTER(struct__XDisplay)))), ('byte_order', c_int), ('bitmap_unit', c_int), ('bitmap_pad', c_int), ('bitmap_bit_order', c_int), ('nformats', c_int), ('pixmap_format', POINTER(ScreenFormat)), ('private8', c_int), ('release', c_int), ('private9', POINTER(struct__XPrivate)), ('private10', POINTER(struct__XPrivate)), ('qlen', c_int), ('last_request_read', c_ulong), ('request', c_ulong), ('private11', XPointer), ('private12', XPointer), ('private13', XPointer), ('private14', XPointer), ('max_request_size', c_uint), ('db', POINTER(struct__XrmHashBucketRec)), ('private15', POINTER(CFUNCTYPE(c_int, POINTER(struct__XDisplay)))), ('display_name', c_char_p), ('default_screen', c_int), ('nscreens', c_int), ('screens', POINTER(Screen)), ('motion_buffer', c_ulong), ('private16', c_ulong), ('min_keycode', c_int), ('max_keycode', c_int), ('private17', XPointer), ('private18', XPointer), ('private19', c_int), ('xdefaults', c_char_p), ] _XPrivDisplay = POINTER(struct_anon_36) # /usr/include/X11/Xlib.h:561 class struct_anon_37(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'root', 'subwindow', 'time', 'x', 'y', 'x_root', 'y_root', 'state', 'keycode', 'same_screen', ] struct_anon_37._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('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), ] XKeyEvent = struct_anon_37 # /usr/include/X11/Xlib.h:582 XKeyPressedEvent = XKeyEvent # /usr/include/X11/Xlib.h:583 XKeyReleasedEvent = XKeyEvent # /usr/include/X11/Xlib.h:584 class struct_anon_38(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'root', 'subwindow', 'time', 'x', 'y', 'x_root', 'y_root', 'state', 'button', 'same_screen', ] struct_anon_38._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('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), ] XButtonEvent = struct_anon_38 # /usr/include/X11/Xlib.h:600 XButtonPressedEvent = XButtonEvent # /usr/include/X11/Xlib.h:601 XButtonReleasedEvent = XButtonEvent # /usr/include/X11/Xlib.h:602 class struct_anon_39(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'root', 'subwindow', 'time', 'x', 'y', 'x_root', 'y_root', 'state', 'is_hint', 'same_screen', ] struct_anon_39._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('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), ] XMotionEvent = struct_anon_39 # /usr/include/X11/Xlib.h:618 XPointerMovedEvent = XMotionEvent # /usr/include/X11/Xlib.h:619 class struct_anon_40(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'root', 'subwindow', 'time', 'x', 'y', 'x_root', 'y_root', 'mode', 'detail', 'same_screen', 'focus', 'state', ] struct_anon_40._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('root', Window), ('subwindow', Window), ('time', Time), ('x', c_int), ('y', c_int), ('x_root', c_int), ('y_root', c_int), ('mode', c_int), ('detail', c_int), ('same_screen', c_int), ('focus', c_int), ('state', c_uint), ] XCrossingEvent = struct_anon_40 # /usr/include/X11/Xlib.h:641 XEnterWindowEvent = XCrossingEvent # /usr/include/X11/Xlib.h:642 XLeaveWindowEvent = XCrossingEvent # /usr/include/X11/Xlib.h:643 class struct_anon_41(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'mode', 'detail', ] struct_anon_41._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('mode', c_int), ('detail', c_int), ] XFocusChangeEvent = struct_anon_41 # /usr/include/X11/Xlib.h:659 XFocusInEvent = XFocusChangeEvent # /usr/include/X11/Xlib.h:660 XFocusOutEvent = XFocusChangeEvent # /usr/include/X11/Xlib.h:661 class struct_anon_42(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'key_vector', ] struct_anon_42._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('key_vector', c_char * 32), ] XKeymapEvent = struct_anon_42 # /usr/include/X11/Xlib.h:671 class struct_anon_43(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'x', 'y', 'width', 'height', 'count', ] struct_anon_43._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('x', c_int), ('y', c_int), ('width', c_int), ('height', c_int), ('count', c_int), ] XExposeEvent = struct_anon_43 # /usr/include/X11/Xlib.h:682 class struct_anon_44(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'drawable', 'x', 'y', 'width', 'height', 'count', 'major_code', 'minor_code', ] struct_anon_44._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('drawable', Drawable), ('x', c_int), ('y', c_int), ('width', c_int), ('height', c_int), ('count', c_int), ('major_code', c_int), ('minor_code', c_int), ] XGraphicsExposeEvent = struct_anon_44 # /usr/include/X11/Xlib.h:695 class struct_anon_45(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'drawable', 'major_code', 'minor_code', ] struct_anon_45._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('drawable', Drawable), ('major_code', c_int), ('minor_code', c_int), ] XNoExposeEvent = struct_anon_45 # /usr/include/X11/Xlib.h:705 class struct_anon_46(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'state', ] struct_anon_46._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('state', c_int), ] XVisibilityEvent = struct_anon_46 # /usr/include/X11/Xlib.h:714 class struct_anon_47(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'parent', 'window', 'x', 'y', 'width', 'height', 'border_width', 'override_redirect', ] struct_anon_47._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('parent', Window), ('window', Window), ('x', c_int), ('y', c_int), ('width', c_int), ('height', c_int), ('border_width', c_int), ('override_redirect', c_int), ] XCreateWindowEvent = struct_anon_47 # /usr/include/X11/Xlib.h:727 class struct_anon_48(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'event', 'window', ] struct_anon_48._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('event', Window), ('window', Window), ] XDestroyWindowEvent = struct_anon_48 # /usr/include/X11/Xlib.h:736 class struct_anon_49(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'event', 'window', 'from_configure', ] struct_anon_49._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('event', Window), ('window', Window), ('from_configure', c_int), ] XUnmapEvent = struct_anon_49 # /usr/include/X11/Xlib.h:746 class struct_anon_50(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'event', 'window', 'override_redirect', ] struct_anon_50._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('event', Window), ('window', Window), ('override_redirect', c_int), ] XMapEvent = struct_anon_50 # /usr/include/X11/Xlib.h:756 class struct_anon_51(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'parent', 'window', ] struct_anon_51._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('parent', Window), ('window', Window), ] XMapRequestEvent = struct_anon_51 # /usr/include/X11/Xlib.h:765 class struct_anon_52(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'event', 'window', 'parent', 'x', 'y', 'override_redirect', ] struct_anon_52._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('event', Window), ('window', Window), ('parent', Window), ('x', c_int), ('y', c_int), ('override_redirect', c_int), ] XReparentEvent = struct_anon_52 # /usr/include/X11/Xlib.h:777 class struct_anon_53(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'event', 'window', 'x', 'y', 'width', 'height', 'border_width', 'above', 'override_redirect', ] struct_anon_53._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('event', Window), ('window', Window), ('x', c_int), ('y', c_int), ('width', c_int), ('height', c_int), ('border_width', c_int), ('above', Window), ('override_redirect', c_int), ] XConfigureEvent = struct_anon_53 # /usr/include/X11/Xlib.h:791 class struct_anon_54(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'event', 'window', 'x', 'y', ] struct_anon_54._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('event', Window), ('window', Window), ('x', c_int), ('y', c_int), ] XGravityEvent = struct_anon_54 # /usr/include/X11/Xlib.h:801 class struct_anon_55(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'width', 'height', ] struct_anon_55._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('width', c_int), ('height', c_int), ] XResizeRequestEvent = struct_anon_55 # /usr/include/X11/Xlib.h:810 class struct_anon_56(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'parent', 'window', 'x', 'y', 'width', 'height', 'border_width', 'above', 'detail', 'value_mask', ] struct_anon_56._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('parent', Window), ('window', Window), ('x', c_int), ('y', c_int), ('width', c_int), ('height', c_int), ('border_width', c_int), ('above', Window), ('detail', c_int), ('value_mask', c_ulong), ] XConfigureRequestEvent = struct_anon_56 # /usr/include/X11/Xlib.h:825 class struct_anon_57(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'event', 'window', 'place', ] struct_anon_57._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('event', Window), ('window', Window), ('place', c_int), ] XCirculateEvent = struct_anon_57 # /usr/include/X11/Xlib.h:835 class struct_anon_58(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'parent', 'window', 'place', ] struct_anon_58._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('parent', Window), ('window', Window), ('place', c_int), ] XCirculateRequestEvent = struct_anon_58 # /usr/include/X11/Xlib.h:845 class struct_anon_59(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'atom', 'time', 'state', ] struct_anon_59._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('atom', Atom), ('time', Time), ('state', c_int), ] XPropertyEvent = struct_anon_59 # /usr/include/X11/Xlib.h:856 class struct_anon_60(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'selection', 'time', ] struct_anon_60._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('selection', Atom), ('time', Time), ] XSelectionClearEvent = struct_anon_60 # /usr/include/X11/Xlib.h:866 class struct_anon_61(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'owner', 'requestor', 'selection', 'target', 'property', 'time', ] struct_anon_61._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('owner', Window), ('requestor', Window), ('selection', Atom), ('target', Atom), ('property', Atom), ('time', Time), ] XSelectionRequestEvent = struct_anon_61 # /usr/include/X11/Xlib.h:879 class struct_anon_62(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'requestor', 'selection', 'target', 'property', 'time', ] struct_anon_62._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('requestor', Window), ('selection', Atom), ('target', Atom), ('property', Atom), ('time', Time), ] XSelectionEvent = struct_anon_62 # /usr/include/X11/Xlib.h:891 class struct_anon_63(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'colormap', 'new', 'state', ] struct_anon_63._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('colormap', Colormap), ('new', c_int), ('state', c_int), ] XColormapEvent = struct_anon_63 # /usr/include/X11/Xlib.h:906 class struct_anon_64(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'message_type', 'format', 'data', ] class struct_anon_65(Union): __slots__ = [ 'b', 's', 'l', ] struct_anon_65._fields_ = [ ('b', c_char * 20), ('s', c_short * 10), ('l', c_long * 5), ] struct_anon_64._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('message_type', Atom), ('format', c_int), ('data', struct_anon_65), ] XClientMessageEvent = struct_anon_64 # /usr/include/X11/Xlib.h:921 class struct_anon_66(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'request', 'first_keycode', 'count', ] struct_anon_66._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('request', c_int), ('first_keycode', c_int), ('count', c_int), ] XMappingEvent = struct_anon_66 # /usr/include/X11/Xlib.h:933 class struct_anon_67(Structure): __slots__ = [ 'type', 'display', 'resourceid', 'serial', 'error_code', 'request_code', 'minor_code', ] struct_anon_67._fields_ = [ ('type', c_int), ('display', POINTER(Display)), ('resourceid', XID), ('serial', c_ulong), ('error_code', c_ubyte), ('request_code', c_ubyte), ('minor_code', c_ubyte), ] XErrorEvent = struct_anon_67 # /usr/include/X11/Xlib.h:943 class struct_anon_68(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', ] struct_anon_68._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ] XAnyEvent = struct_anon_68 # /usr/include/X11/Xlib.h:951 class struct_anon_69(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'extension', 'evtype', ] struct_anon_69._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('extension', c_int), ('evtype', c_int), ] XGenericEvent = struct_anon_69 # /usr/include/X11/Xlib.h:967 class struct_anon_70(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'extension', 'evtype', 'cookie', 'data', ] struct_anon_70._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('extension', c_int), ('evtype', c_int), ('cookie', c_uint), ('data', POINTER(None)), ] XGenericEventCookie = struct_anon_70 # /usr/include/X11/Xlib.h:978 class struct__XEvent(Union): __slots__ = [ 'type', 'xany', 'xkey', 'xbutton', 'xmotion', 'xcrossing', 'xfocus', 'xexpose', 'xgraphicsexpose', 'xnoexpose', 'xvisibility', 'xcreatewindow', 'xdestroywindow', 'xunmap', 'xmap', 'xmaprequest', 'xreparent', 'xconfigure', 'xgravity', 'xresizerequest', 'xconfigurerequest', 'xcirculate', 'xcirculaterequest', 'xproperty', 'xselectionclear', 'xselectionrequest', 'xselection', 'xcolormap', 'xclient', 'xmapping', 'xerror', 'xkeymap', 'xgeneric', 'xcookie', 'pad', ] struct__XEvent._fields_ = [ ('type', c_int), ('xany', XAnyEvent), ('xkey', XKeyEvent), ('xbutton', XButtonEvent), ('xmotion', XMotionEvent), ('xcrossing', XCrossingEvent), ('xfocus', XFocusChangeEvent), ('xexpose', XExposeEvent), ('xgraphicsexpose', XGraphicsExposeEvent), ('xnoexpose', XNoExposeEvent), ('xvisibility', XVisibilityEvent), ('xcreatewindow', XCreateWindowEvent), ('xdestroywindow', XDestroyWindowEvent), ('xunmap', XUnmapEvent), ('xmap', XMapEvent), ('xmaprequest', XMapRequestEvent), ('xreparent', XReparentEvent), ('xconfigure', XConfigureEvent), ('xgravity', XGravityEvent), ('xresizerequest', XResizeRequestEvent), ('xconfigurerequest', XConfigureRequestEvent), ('xcirculate', XCirculateEvent), ('xcirculaterequest', XCirculateRequestEvent), ('xproperty', XPropertyEvent), ('xselectionclear', XSelectionClearEvent), ('xselectionrequest', XSelectionRequestEvent), ('xselection', XSelectionEvent), ('xcolormap', XColormapEvent), ('xclient', XClientMessageEvent), ('xmapping', XMappingEvent), ('xerror', XErrorEvent), ('xkeymap', XKeymapEvent), ('xgeneric', XGenericEvent), ('xcookie', XGenericEventCookie), ('pad', c_long * 24), ] XEvent = struct__XEvent # /usr/include/X11/Xlib.h:1020 class struct_anon_71(Structure): __slots__ = [ 'lbearing', 'rbearing', 'width', 'ascent', 'descent', 'attributes', ] struct_anon_71._fields_ = [ ('lbearing', c_short), ('rbearing', c_short), ('width', c_short), ('ascent', c_short), ('descent', c_short), ('attributes', c_ushort), ] XCharStruct = struct_anon_71 # /usr/include/X11/Xlib.h:1035 class struct_anon_72(Structure): __slots__ = [ 'name', 'card32', ] struct_anon_72._fields_ = [ ('name', Atom), ('card32', c_ulong), ] XFontProp = struct_anon_72 # /usr/include/X11/Xlib.h:1044 class struct_anon_73(Structure): __slots__ = [ 'ext_data', 'fid', 'direction', 'min_char_or_byte2', 'max_char_or_byte2', 'min_byte1', 'max_byte1', 'all_chars_exist', 'default_char', 'n_properties', 'properties', 'min_bounds', 'max_bounds', 'per_char', 'ascent', 'descent', ] struct_anon_73._fields_ = [ ('ext_data', POINTER(XExtData)), ('fid', Font), ('direction', c_uint), ('min_char_or_byte2', c_uint), ('max_char_or_byte2', c_uint), ('min_byte1', c_uint), ('max_byte1', c_uint), ('all_chars_exist', c_int), ('default_char', c_uint), ('n_properties', c_int), ('properties', POINTER(XFontProp)), ('min_bounds', XCharStruct), ('max_bounds', XCharStruct), ('per_char', POINTER(XCharStruct)), ('ascent', c_int), ('descent', c_int), ] XFontStruct = struct_anon_73 # /usr/include/X11/Xlib.h:1063 class struct_anon_74(Structure): __slots__ = [ 'chars', 'nchars', 'delta', 'font', ] struct_anon_74._fields_ = [ ('chars', c_char_p), ('nchars', c_int), ('delta', c_int), ('font', Font), ] XTextItem = struct_anon_74 # /usr/include/X11/Xlib.h:1073 class struct_anon_75(Structure): __slots__ = [ 'byte1', 'byte2', ] struct_anon_75._fields_ = [ ('byte1', c_ubyte), ('byte2', c_ubyte), ] XChar2b = struct_anon_75 # /usr/include/X11/Xlib.h:1078 class struct_anon_76(Structure): __slots__ = [ 'chars', 'nchars', 'delta', 'font', ] struct_anon_76._fields_ = [ ('chars', POINTER(XChar2b)), ('nchars', c_int), ('delta', c_int), ('font', Font), ] XTextItem16 = struct_anon_76 # /usr/include/X11/Xlib.h:1085 class struct_anon_77(Union): __slots__ = [ 'display', 'gc', 'visual', 'screen', 'pixmap_format', 'font', ] struct_anon_77._fields_ = [ ('display', POINTER(Display)), ('gc', GC), ('visual', POINTER(Visual)), ('screen', POINTER(Screen)), ('pixmap_format', POINTER(ScreenFormat)), ('font', POINTER(XFontStruct)), ] XEDataObject = struct_anon_77 # /usr/include/X11/Xlib.h:1093 class struct_anon_78(Structure): __slots__ = [ 'max_ink_extent', 'max_logical_extent', ] struct_anon_78._fields_ = [ ('max_ink_extent', XRectangle), ('max_logical_extent', XRectangle), ] XFontSetExtents = struct_anon_78 # /usr/include/X11/Xlib.h:1098 class struct__XOM(Structure): __slots__ = [ ] struct__XOM._fields_ = [ ('_opaque_struct', c_int) ] class struct__XOM(Structure): __slots__ = [ ] struct__XOM._fields_ = [ ('_opaque_struct', c_int) ] XOM = POINTER(struct__XOM) # /usr/include/X11/Xlib.h:1104 class struct__XOC(Structure): __slots__ = [ ] struct__XOC._fields_ = [ ('_opaque_struct', c_int) ] class struct__XOC(Structure): __slots__ = [ ] struct__XOC._fields_ = [ ('_opaque_struct', c_int) ] XOC = POINTER(struct__XOC) # /usr/include/X11/Xlib.h:1105 class struct__XOC(Structure): __slots__ = [ ] struct__XOC._fields_ = [ ('_opaque_struct', c_int) ] class struct__XOC(Structure): __slots__ = [ ] struct__XOC._fields_ = [ ('_opaque_struct', c_int) ] XFontSet = POINTER(struct__XOC) # /usr/include/X11/Xlib.h:1105 class struct_anon_79(Structure): __slots__ = [ 'chars', 'nchars', 'delta', 'font_set', ] struct_anon_79._fields_ = [ ('chars', c_char_p), ('nchars', c_int), ('delta', c_int), ('font_set', XFontSet), ] XmbTextItem = struct_anon_79 # /usr/include/X11/Xlib.h:1112 class struct_anon_80(Structure): __slots__ = [ 'chars', 'nchars', 'delta', 'font_set', ] struct_anon_80._fields_ = [ ('chars', c_wchar_p), ('nchars', c_int), ('delta', c_int), ('font_set', XFontSet), ] XwcTextItem = struct_anon_80 # /usr/include/X11/Xlib.h:1119 class struct_anon_81(Structure): __slots__ = [ 'charset_count', 'charset_list', ] struct_anon_81._fields_ = [ ('charset_count', c_int), ('charset_list', POINTER(c_char_p)), ] XOMCharSetList = struct_anon_81 # /usr/include/X11/Xlib.h:1135 enum_anon_82 = c_int XOMOrientation_LTR_TTB = 0 XOMOrientation_RTL_TTB = 1 XOMOrientation_TTB_LTR = 2 XOMOrientation_TTB_RTL = 3 XOMOrientation_Context = 4 XOrientation = enum_anon_82 # /usr/include/X11/Xlib.h:1143 class struct_anon_83(Structure): __slots__ = [ 'num_orientation', 'orientation', ] struct_anon_83._fields_ = [ ('num_orientation', c_int), ('orientation', POINTER(XOrientation)), ] XOMOrientation = struct_anon_83 # /usr/include/X11/Xlib.h:1148 class struct_anon_84(Structure): __slots__ = [ 'num_font', 'font_struct_list', 'font_name_list', ] struct_anon_84._fields_ = [ ('num_font', c_int), ('font_struct_list', POINTER(POINTER(XFontStruct))), ('font_name_list', POINTER(c_char_p)), ] XOMFontInfo = struct_anon_84 # /usr/include/X11/Xlib.h:1154 class struct__XIM(Structure): __slots__ = [ ] struct__XIM._fields_ = [ ('_opaque_struct', c_int) ] class struct__XIM(Structure): __slots__ = [ ] struct__XIM._fields_ = [ ('_opaque_struct', c_int) ] XIM = POINTER(struct__XIM) # /usr/include/X11/Xlib.h:1156 class struct__XIC(Structure): __slots__ = [ ] struct__XIC._fields_ = [ ('_opaque_struct', c_int) ] class struct__XIC(Structure): __slots__ = [ ] struct__XIC._fields_ = [ ('_opaque_struct', c_int) ] XIC = POINTER(struct__XIC) # /usr/include/X11/Xlib.h:1157 XIMProc = CFUNCTYPE(None, XIM, XPointer, XPointer) # /usr/include/X11/Xlib.h:1159 XICProc = CFUNCTYPE(c_int, XIC, XPointer, XPointer) # /usr/include/X11/Xlib.h:1165 XIDProc = CFUNCTYPE(None, POINTER(Display), XPointer, XPointer) # /usr/include/X11/Xlib.h:1171 XIMStyle = c_ulong # /usr/include/X11/Xlib.h:1177 class struct_anon_85(Structure): __slots__ = [ 'count_styles', 'supported_styles', ] struct_anon_85._fields_ = [ ('count_styles', c_ushort), ('supported_styles', POINTER(XIMStyle)), ] XIMStyles = struct_anon_85 # /usr/include/X11/Xlib.h:1182 XIMPreeditArea = 1 # /usr/include/X11/Xlib.h:1184 XIMPreeditCallbacks = 2 # /usr/include/X11/Xlib.h:1185 XIMPreeditPosition = 4 # /usr/include/X11/Xlib.h:1186 XIMPreeditNothing = 8 # /usr/include/X11/Xlib.h:1187 XIMPreeditNone = 16 # /usr/include/X11/Xlib.h:1188 XIMStatusArea = 256 # /usr/include/X11/Xlib.h:1189 XIMStatusCallbacks = 512 # /usr/include/X11/Xlib.h:1190 XIMStatusNothing = 1024 # /usr/include/X11/Xlib.h:1191 XIMStatusNone = 2048 # /usr/include/X11/Xlib.h:1192 XBufferOverflow = -1 # /usr/include/X11/Xlib.h:1238 XLookupNone = 1 # /usr/include/X11/Xlib.h:1239 XLookupChars = 2 # /usr/include/X11/Xlib.h:1240 XLookupKeySym = 3 # /usr/include/X11/Xlib.h:1241 XLookupBoth = 4 # /usr/include/X11/Xlib.h:1242 XVaNestedList = POINTER(None) # /usr/include/X11/Xlib.h:1244 class struct_anon_86(Structure): __slots__ = [ 'client_data', 'callback', ] struct_anon_86._fields_ = [ ('client_data', XPointer), ('callback', XIMProc), ] XIMCallback = struct_anon_86 # /usr/include/X11/Xlib.h:1249 class struct_anon_87(Structure): __slots__ = [ 'client_data', 'callback', ] struct_anon_87._fields_ = [ ('client_data', XPointer), ('callback', XICProc), ] XICCallback = struct_anon_87 # /usr/include/X11/Xlib.h:1254 XIMFeedback = c_ulong # /usr/include/X11/Xlib.h:1256 XIMReverse = 1 # /usr/include/X11/Xlib.h:1258 XIMUnderline = 2 # /usr/include/X11/Xlib.h:1259 XIMHighlight = 4 # /usr/include/X11/Xlib.h:1260 XIMPrimary = 32 # /usr/include/X11/Xlib.h:1261 XIMSecondary = 64 # /usr/include/X11/Xlib.h:1262 XIMTertiary = 128 # /usr/include/X11/Xlib.h:1263 XIMVisibleToForward = 256 # /usr/include/X11/Xlib.h:1264 XIMVisibleToBackword = 512 # /usr/include/X11/Xlib.h:1265 XIMVisibleToCenter = 1024 # /usr/include/X11/Xlib.h:1266 class struct__XIMText(Structure): __slots__ = [ 'length', 'feedback', 'encoding_is_wchar', 'string', ] class struct_anon_88(Union): __slots__ = [ 'multi_byte', 'wide_char', ] struct_anon_88._fields_ = [ ('multi_byte', c_char_p), ('wide_char', c_wchar_p), ] struct__XIMText._fields_ = [ ('length', c_ushort), ('feedback', POINTER(XIMFeedback)), ('encoding_is_wchar', c_int), ('string', struct_anon_88), ] XIMText = struct__XIMText # /usr/include/X11/Xlib.h:1276 XIMPreeditState = c_ulong # /usr/include/X11/Xlib.h:1278 XIMPreeditUnKnown = 0 # /usr/include/X11/Xlib.h:1280 XIMPreeditEnable = 1 # /usr/include/X11/Xlib.h:1281 XIMPreeditDisable = 2 # /usr/include/X11/Xlib.h:1282 class struct__XIMPreeditStateNotifyCallbackStruct(Structure): __slots__ = [ 'state', ] struct__XIMPreeditStateNotifyCallbackStruct._fields_ = [ ('state', XIMPreeditState), ] XIMPreeditStateNotifyCallbackStruct = struct__XIMPreeditStateNotifyCallbackStruct # /usr/include/X11/Xlib.h:1286 XIMResetState = c_ulong # /usr/include/X11/Xlib.h:1288 XIMInitialState = 1 # /usr/include/X11/Xlib.h:1290 XIMPreserveState = 2 # /usr/include/X11/Xlib.h:1291 XIMStringConversionFeedback = c_ulong # /usr/include/X11/Xlib.h:1293 XIMStringConversionLeftEdge = 1 # /usr/include/X11/Xlib.h:1295 XIMStringConversionRightEdge = 2 # /usr/include/X11/Xlib.h:1296 XIMStringConversionTopEdge = 4 # /usr/include/X11/Xlib.h:1297 XIMStringConversionBottomEdge = 8 # /usr/include/X11/Xlib.h:1298 XIMStringConversionConcealed = 16 # /usr/include/X11/Xlib.h:1299 XIMStringConversionWrapped = 32 # /usr/include/X11/Xlib.h:1300 class struct__XIMStringConversionText(Structure): __slots__ = [ 'length', 'feedback', 'encoding_is_wchar', 'string', ] class struct_anon_89(Union): __slots__ = [ 'mbs', 'wcs', ] struct_anon_89._fields_ = [ ('mbs', c_char_p), ('wcs', c_wchar_p), ] struct__XIMStringConversionText._fields_ = [ ('length', c_ushort), ('feedback', POINTER(XIMStringConversionFeedback)), ('encoding_is_wchar', c_int), ('string', struct_anon_89), ] XIMStringConversionText = struct__XIMStringConversionText # /usr/include/X11/Xlib.h:1310 XIMStringConversionPosition = c_ushort # /usr/include/X11/Xlib.h:1312 XIMStringConversionType = c_ushort # /usr/include/X11/Xlib.h:1314 XIMStringConversionBuffer = 1 # /usr/include/X11/Xlib.h:1316 XIMStringConversionLine = 2 # /usr/include/X11/Xlib.h:1317 XIMStringConversionWord = 3 # /usr/include/X11/Xlib.h:1318 XIMStringConversionChar = 4 # /usr/include/X11/Xlib.h:1319 XIMStringConversionOperation = c_ushort # /usr/include/X11/Xlib.h:1321 XIMStringConversionSubstitution = 1 # /usr/include/X11/Xlib.h:1323 XIMStringConversionRetrieval = 2 # /usr/include/X11/Xlib.h:1324 enum_anon_90 = c_int XIMForwardChar = 0 XIMBackwardChar = 1 XIMForwardWord = 2 XIMBackwardWord = 3 XIMCaretUp = 4 XIMCaretDown = 5 XIMNextLine = 6 XIMPreviousLine = 7 XIMLineStart = 8 XIMLineEnd = 9 XIMAbsolutePosition = 10 XIMDontChange = 11 XIMCaretDirection = enum_anon_90 # /usr/include/X11/Xlib.h:1334 class struct__XIMStringConversionCallbackStruct(Structure): __slots__ = [ 'position', 'direction', 'operation', 'factor', 'text', ] struct__XIMStringConversionCallbackStruct._fields_ = [ ('position', XIMStringConversionPosition), ('direction', XIMCaretDirection), ('operation', XIMStringConversionOperation), ('factor', c_ushort), ('text', POINTER(XIMStringConversionText)), ] XIMStringConversionCallbackStruct = struct__XIMStringConversionCallbackStruct # /usr/include/X11/Xlib.h:1342 class struct__XIMPreeditDrawCallbackStruct(Structure): __slots__ = [ 'caret', 'chg_first', 'chg_length', 'text', ] struct__XIMPreeditDrawCallbackStruct._fields_ = [ ('caret', c_int), ('chg_first', c_int), ('chg_length', c_int), ('text', POINTER(XIMText)), ] XIMPreeditDrawCallbackStruct = struct__XIMPreeditDrawCallbackStruct # /usr/include/X11/Xlib.h:1349 enum_anon_91 = c_int XIMIsInvisible = 0 XIMIsPrimary = 1 XIMIsSecondary = 2 XIMCaretStyle = enum_anon_91 # /usr/include/X11/Xlib.h:1355 class struct__XIMPreeditCaretCallbackStruct(Structure): __slots__ = [ 'position', 'direction', 'style', ] struct__XIMPreeditCaretCallbackStruct._fields_ = [ ('position', c_int), ('direction', XIMCaretDirection), ('style', XIMCaretStyle), ] XIMPreeditCaretCallbackStruct = struct__XIMPreeditCaretCallbackStruct # /usr/include/X11/Xlib.h:1361 enum_anon_92 = c_int XIMTextType = 0 XIMBitmapType = 1 XIMStatusDataType = enum_anon_92 # /usr/include/X11/Xlib.h:1366 class struct__XIMStatusDrawCallbackStruct(Structure): __slots__ = [ 'type', 'data', ] class struct_anon_93(Union): __slots__ = [ 'text', 'bitmap', ] struct_anon_93._fields_ = [ ('text', POINTER(XIMText)), ('bitmap', Pixmap), ] struct__XIMStatusDrawCallbackStruct._fields_ = [ ('type', XIMStatusDataType), ('data', struct_anon_93), ] XIMStatusDrawCallbackStruct = struct__XIMStatusDrawCallbackStruct # /usr/include/X11/Xlib.h:1374 class struct__XIMHotKeyTrigger(Structure): __slots__ = [ 'keysym', 'modifier', 'modifier_mask', ] struct__XIMHotKeyTrigger._fields_ = [ ('keysym', KeySym), ('modifier', c_int), ('modifier_mask', c_int), ] XIMHotKeyTrigger = struct__XIMHotKeyTrigger # /usr/include/X11/Xlib.h:1380 class struct__XIMHotKeyTriggers(Structure): __slots__ = [ 'num_hot_key', 'key', ] struct__XIMHotKeyTriggers._fields_ = [ ('num_hot_key', c_int), ('key', POINTER(XIMHotKeyTrigger)), ] XIMHotKeyTriggers = struct__XIMHotKeyTriggers # /usr/include/X11/Xlib.h:1385 XIMHotKeyState = c_ulong # /usr/include/X11/Xlib.h:1387 XIMHotKeyStateON = 1 # /usr/include/X11/Xlib.h:1389 XIMHotKeyStateOFF = 2 # /usr/include/X11/Xlib.h:1390 class struct_anon_94(Structure): __slots__ = [ 'count_values', 'supported_values', ] struct_anon_94._fields_ = [ ('count_values', c_ushort), ('supported_values', POINTER(c_char_p)), ] XIMValuesList = struct_anon_94 # /usr/include/X11/Xlib.h:1395 # /usr/include/X11/Xlib.h:1405 XLoadQueryFont = _lib.XLoadQueryFont XLoadQueryFont.restype = POINTER(XFontStruct) XLoadQueryFont.argtypes = [POINTER(Display), c_char_p] # /usr/include/X11/Xlib.h:1410 XQueryFont = _lib.XQueryFont XQueryFont.restype = POINTER(XFontStruct) XQueryFont.argtypes = [POINTER(Display), XID] # /usr/include/X11/Xlib.h:1416 XGetMotionEvents = _lib.XGetMotionEvents XGetMotionEvents.restype = POINTER(XTimeCoord) XGetMotionEvents.argtypes = [POINTER(Display), Window, Time, Time, POINTER(c_int)] # /usr/include/X11/Xlib.h:1424 XDeleteModifiermapEntry = _lib.XDeleteModifiermapEntry XDeleteModifiermapEntry.restype = POINTER(XModifierKeymap) XDeleteModifiermapEntry.argtypes = [POINTER(XModifierKeymap), KeyCode, c_int] # /usr/include/X11/Xlib.h:1434 XGetModifierMapping = _lib.XGetModifierMapping XGetModifierMapping.restype = POINTER(XModifierKeymap) XGetModifierMapping.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1438 XInsertModifiermapEntry = _lib.XInsertModifiermapEntry XInsertModifiermapEntry.restype = POINTER(XModifierKeymap) XInsertModifiermapEntry.argtypes = [POINTER(XModifierKeymap), KeyCode, c_int] # /usr/include/X11/Xlib.h:1448 XNewModifiermap = _lib.XNewModifiermap XNewModifiermap.restype = POINTER(XModifierKeymap) XNewModifiermap.argtypes = [c_int] # /usr/include/X11/Xlib.h:1452 XCreateImage = _lib.XCreateImage XCreateImage.restype = POINTER(XImage) XCreateImage.argtypes = [POINTER(Display), POINTER(Visual), c_uint, c_int, c_int, c_char_p, c_uint, c_uint, c_int, c_int] # /usr/include/X11/Xlib.h:1464 XInitImage = _lib.XInitImage XInitImage.restype = c_int XInitImage.argtypes = [POINTER(XImage)] # /usr/include/X11/Xlib.h:1467 XGetImage = _lib.XGetImage XGetImage.restype = POINTER(XImage) XGetImage.argtypes = [POINTER(Display), Drawable, c_int, c_int, c_uint, c_uint, c_ulong, c_int] # /usr/include/X11/Xlib.h:1477 XGetSubImage = _lib.XGetSubImage XGetSubImage.restype = POINTER(XImage) XGetSubImage.argtypes = [POINTER(Display), Drawable, c_int, c_int, c_uint, c_uint, c_ulong, c_int, POINTER(XImage), c_int, c_int] # /usr/include/X11/Xlib.h:1494 XOpenDisplay = _lib.XOpenDisplay XOpenDisplay.restype = POINTER(Display) XOpenDisplay.argtypes = [c_char_p] # /usr/include/X11/Xlib.h:1498 XrmInitialize = _lib.XrmInitialize XrmInitialize.restype = None XrmInitialize.argtypes = [] # /usr/include/X11/Xlib.h:1502 XFetchBytes = _lib.XFetchBytes XFetchBytes.restype = c_char_p XFetchBytes.argtypes = [POINTER(Display), POINTER(c_int)] # /usr/include/X11/Xlib.h:1506 XFetchBuffer = _lib.XFetchBuffer XFetchBuffer.restype = c_char_p XFetchBuffer.argtypes = [POINTER(Display), POINTER(c_int), c_int] # /usr/include/X11/Xlib.h:1511 XGetAtomName = _lib.XGetAtomName XGetAtomName.restype = c_char_p XGetAtomName.argtypes = [POINTER(Display), Atom] # /usr/include/X11/Xlib.h:1515 XGetAtomNames = _lib.XGetAtomNames XGetAtomNames.restype = c_int XGetAtomNames.argtypes = [POINTER(Display), POINTER(Atom), c_int, POINTER(c_char_p)] # /usr/include/X11/Xlib.h:1521 XGetDefault = _lib.XGetDefault XGetDefault.restype = c_char_p XGetDefault.argtypes = [POINTER(Display), c_char_p, c_char_p] # /usr/include/X11/Xlib.h:1526 XDisplayName = _lib.XDisplayName XDisplayName.restype = c_char_p XDisplayName.argtypes = [c_char_p] # /usr/include/X11/Xlib.h:1529 XKeysymToString = _lib.XKeysymToString XKeysymToString.restype = c_char_p XKeysymToString.argtypes = [KeySym] # /usr/include/X11/Xlib.h:1533 XSynchronize = _lib.XSynchronize XSynchronize.restype = POINTER(CFUNCTYPE(c_int, POINTER(Display))) XSynchronize.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:1539 XSetAfterFunction = _lib.XSetAfterFunction XSetAfterFunction.restype = POINTER(CFUNCTYPE(c_int, POINTER(Display))) XSetAfterFunction.argtypes = [POINTER(Display), CFUNCTYPE(c_int, POINTER(Display))] # /usr/include/X11/Xlib.h:1547 XInternAtom = _lib.XInternAtom XInternAtom.restype = Atom XInternAtom.argtypes = [POINTER(Display), c_char_p, c_int] # /usr/include/X11/Xlib.h:1552 XInternAtoms = _lib.XInternAtoms XInternAtoms.restype = c_int XInternAtoms.argtypes = [POINTER(Display), POINTER(c_char_p), c_int, c_int, POINTER(Atom)] # /usr/include/X11/Xlib.h:1559 XCopyColormapAndFree = _lib.XCopyColormapAndFree XCopyColormapAndFree.restype = Colormap XCopyColormapAndFree.argtypes = [POINTER(Display), Colormap] # /usr/include/X11/Xlib.h:1563 XCreateColormap = _lib.XCreateColormap XCreateColormap.restype = Colormap XCreateColormap.argtypes = [POINTER(Display), Window, POINTER(Visual), c_int] # /usr/include/X11/Xlib.h:1569 XCreatePixmapCursor = _lib.XCreatePixmapCursor XCreatePixmapCursor.restype = Cursor XCreatePixmapCursor.argtypes = [POINTER(Display), Pixmap, Pixmap, POINTER(XColor), POINTER(XColor), c_uint, c_uint] # /usr/include/X11/Xlib.h:1578 XCreateGlyphCursor = _lib.XCreateGlyphCursor XCreateGlyphCursor.restype = Cursor XCreateGlyphCursor.argtypes = [POINTER(Display), Font, Font, c_uint, c_uint, POINTER(XColor), POINTER(XColor)] # /usr/include/X11/Xlib.h:1587 XCreateFontCursor = _lib.XCreateFontCursor XCreateFontCursor.restype = Cursor XCreateFontCursor.argtypes = [POINTER(Display), c_uint] # /usr/include/X11/Xlib.h:1591 XLoadFont = _lib.XLoadFont XLoadFont.restype = Font XLoadFont.argtypes = [POINTER(Display), c_char_p] # /usr/include/X11/Xlib.h:1595 XCreateGC = _lib.XCreateGC XCreateGC.restype = GC XCreateGC.argtypes = [POINTER(Display), Drawable, c_ulong, POINTER(XGCValues)] # /usr/include/X11/Xlib.h:1601 XGContextFromGC = _lib.XGContextFromGC XGContextFromGC.restype = GContext XGContextFromGC.argtypes = [GC] # /usr/include/X11/Xlib.h:1604 XFlushGC = _lib.XFlushGC XFlushGC.restype = None XFlushGC.argtypes = [POINTER(Display), GC] # /usr/include/X11/Xlib.h:1608 XCreatePixmap = _lib.XCreatePixmap XCreatePixmap.restype = Pixmap XCreatePixmap.argtypes = [POINTER(Display), Drawable, c_uint, c_uint, c_uint] # /usr/include/X11/Xlib.h:1615 XCreateBitmapFromData = _lib.XCreateBitmapFromData XCreateBitmapFromData.restype = Pixmap XCreateBitmapFromData.argtypes = [POINTER(Display), Drawable, c_char_p, c_uint, c_uint] # /usr/include/X11/Xlib.h:1622 XCreatePixmapFromBitmapData = _lib.XCreatePixmapFromBitmapData XCreatePixmapFromBitmapData.restype = Pixmap XCreatePixmapFromBitmapData.argtypes = [POINTER(Display), Drawable, c_char_p, c_uint, c_uint, c_ulong, c_ulong, c_uint] # /usr/include/X11/Xlib.h:1632 XCreateSimpleWindow = _lib.XCreateSimpleWindow XCreateSimpleWindow.restype = Window XCreateSimpleWindow.argtypes = [POINTER(Display), Window, c_int, c_int, c_uint, c_uint, c_uint, c_ulong, c_ulong] # /usr/include/X11/Xlib.h:1643 XGetSelectionOwner = _lib.XGetSelectionOwner XGetSelectionOwner.restype = Window XGetSelectionOwner.argtypes = [POINTER(Display), Atom] # /usr/include/X11/Xlib.h:1647 XCreateWindow = _lib.XCreateWindow XCreateWindow.restype = Window XCreateWindow.argtypes = [POINTER(Display), Window, c_int, c_int, c_uint, c_uint, c_uint, c_int, c_uint, POINTER(Visual), c_ulong, POINTER(XSetWindowAttributes)] # /usr/include/X11/Xlib.h:1661 XListInstalledColormaps = _lib.XListInstalledColormaps XListInstalledColormaps.restype = POINTER(Colormap) XListInstalledColormaps.argtypes = [POINTER(Display), Window, POINTER(c_int)] # /usr/include/X11/Xlib.h:1666 XListFonts = _lib.XListFonts XListFonts.restype = POINTER(c_char_p) XListFonts.argtypes = [POINTER(Display), c_char_p, c_int, POINTER(c_int)] # /usr/include/X11/Xlib.h:1672 XListFontsWithInfo = _lib.XListFontsWithInfo XListFontsWithInfo.restype = POINTER(c_char_p) XListFontsWithInfo.argtypes = [POINTER(Display), c_char_p, c_int, POINTER(c_int), POINTER(POINTER(XFontStruct))] # /usr/include/X11/Xlib.h:1679 XGetFontPath = _lib.XGetFontPath XGetFontPath.restype = POINTER(c_char_p) XGetFontPath.argtypes = [POINTER(Display), POINTER(c_int)] # /usr/include/X11/Xlib.h:1683 XListExtensions = _lib.XListExtensions XListExtensions.restype = POINTER(c_char_p) XListExtensions.argtypes = [POINTER(Display), POINTER(c_int)] # /usr/include/X11/Xlib.h:1687 XListProperties = _lib.XListProperties XListProperties.restype = POINTER(Atom) XListProperties.argtypes = [POINTER(Display), Window, POINTER(c_int)] # /usr/include/X11/Xlib.h:1692 XListHosts = _lib.XListHosts XListHosts.restype = POINTER(XHostAddress) XListHosts.argtypes = [POINTER(Display), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xlib.h:1697 XKeycodeToKeysym = _lib.XKeycodeToKeysym XKeycodeToKeysym.restype = KeySym XKeycodeToKeysym.argtypes = [POINTER(Display), KeyCode, c_int] # /usr/include/X11/Xlib.h:1706 XLookupKeysym = _lib.XLookupKeysym XLookupKeysym.restype = KeySym XLookupKeysym.argtypes = [POINTER(XKeyEvent), c_int] # /usr/include/X11/Xlib.h:1710 XGetKeyboardMapping = _lib.XGetKeyboardMapping XGetKeyboardMapping.restype = POINTER(KeySym) XGetKeyboardMapping.argtypes = [POINTER(Display), KeyCode, c_int, POINTER(c_int)] # /usr/include/X11/Xlib.h:1720 XStringToKeysym = _lib.XStringToKeysym XStringToKeysym.restype = KeySym XStringToKeysym.argtypes = [c_char_p] # /usr/include/X11/Xlib.h:1723 XMaxRequestSize = _lib.XMaxRequestSize XMaxRequestSize.restype = c_long XMaxRequestSize.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1726 XExtendedMaxRequestSize = _lib.XExtendedMaxRequestSize XExtendedMaxRequestSize.restype = c_long XExtendedMaxRequestSize.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1729 XResourceManagerString = _lib.XResourceManagerString XResourceManagerString.restype = c_char_p XResourceManagerString.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1732 XScreenResourceString = _lib.XScreenResourceString XScreenResourceString.restype = c_char_p XScreenResourceString.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1735 XDisplayMotionBufferSize = _lib.XDisplayMotionBufferSize XDisplayMotionBufferSize.restype = c_ulong XDisplayMotionBufferSize.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1738 XVisualIDFromVisual = _lib.XVisualIDFromVisual XVisualIDFromVisual.restype = VisualID XVisualIDFromVisual.argtypes = [POINTER(Visual)] # /usr/include/X11/Xlib.h:1744 XInitThreads = _lib.XInitThreads XInitThreads.restype = c_int XInitThreads.argtypes = [] # /usr/include/X11/Xlib.h:1748 XLockDisplay = _lib.XLockDisplay XLockDisplay.restype = None XLockDisplay.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1752 XUnlockDisplay = _lib.XUnlockDisplay XUnlockDisplay.restype = None XUnlockDisplay.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1758 XInitExtension = _lib.XInitExtension XInitExtension.restype = POINTER(XExtCodes) XInitExtension.argtypes = [POINTER(Display), c_char_p] # /usr/include/X11/Xlib.h:1763 XAddExtension = _lib.XAddExtension XAddExtension.restype = POINTER(XExtCodes) XAddExtension.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1766 XFindOnExtensionList = _lib.XFindOnExtensionList XFindOnExtensionList.restype = POINTER(XExtData) XFindOnExtensionList.argtypes = [POINTER(POINTER(XExtData)), c_int] # /usr/include/X11/Xlib.h:1770 XEHeadOfExtensionList = _lib.XEHeadOfExtensionList XEHeadOfExtensionList.restype = POINTER(POINTER(XExtData)) XEHeadOfExtensionList.argtypes = [XEDataObject] # /usr/include/X11/Xlib.h:1775 XRootWindow = _lib.XRootWindow XRootWindow.restype = Window XRootWindow.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:1779 XDefaultRootWindow = _lib.XDefaultRootWindow XDefaultRootWindow.restype = Window XDefaultRootWindow.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1782 XRootWindowOfScreen = _lib.XRootWindowOfScreen XRootWindowOfScreen.restype = Window XRootWindowOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1785 XDefaultVisual = _lib.XDefaultVisual XDefaultVisual.restype = POINTER(Visual) XDefaultVisual.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:1789 XDefaultVisualOfScreen = _lib.XDefaultVisualOfScreen XDefaultVisualOfScreen.restype = POINTER(Visual) XDefaultVisualOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1792 XDefaultGC = _lib.XDefaultGC XDefaultGC.restype = GC XDefaultGC.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:1796 XDefaultGCOfScreen = _lib.XDefaultGCOfScreen XDefaultGCOfScreen.restype = GC XDefaultGCOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1799 XBlackPixel = _lib.XBlackPixel XBlackPixel.restype = c_ulong XBlackPixel.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:1803 XWhitePixel = _lib.XWhitePixel XWhitePixel.restype = c_ulong XWhitePixel.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:1807 XAllPlanes = _lib.XAllPlanes XAllPlanes.restype = c_ulong XAllPlanes.argtypes = [] # /usr/include/X11/Xlib.h:1810 XBlackPixelOfScreen = _lib.XBlackPixelOfScreen XBlackPixelOfScreen.restype = c_ulong XBlackPixelOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1813 XWhitePixelOfScreen = _lib.XWhitePixelOfScreen XWhitePixelOfScreen.restype = c_ulong XWhitePixelOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1816 XNextRequest = _lib.XNextRequest XNextRequest.restype = c_ulong XNextRequest.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1819 XLastKnownRequestProcessed = _lib.XLastKnownRequestProcessed XLastKnownRequestProcessed.restype = c_ulong XLastKnownRequestProcessed.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1822 XServerVendor = _lib.XServerVendor XServerVendor.restype = c_char_p XServerVendor.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1825 XDisplayString = _lib.XDisplayString XDisplayString.restype = c_char_p XDisplayString.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1828 XDefaultColormap = _lib.XDefaultColormap XDefaultColormap.restype = Colormap XDefaultColormap.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:1832 XDefaultColormapOfScreen = _lib.XDefaultColormapOfScreen XDefaultColormapOfScreen.restype = Colormap XDefaultColormapOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1835 XDisplayOfScreen = _lib.XDisplayOfScreen XDisplayOfScreen.restype = POINTER(Display) XDisplayOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1838 XScreenOfDisplay = _lib.XScreenOfDisplay XScreenOfDisplay.restype = POINTER(Screen) XScreenOfDisplay.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:1842 XDefaultScreenOfDisplay = _lib.XDefaultScreenOfDisplay XDefaultScreenOfDisplay.restype = POINTER(Screen) XDefaultScreenOfDisplay.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1845 XEventMaskOfScreen = _lib.XEventMaskOfScreen XEventMaskOfScreen.restype = c_long XEventMaskOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1849 XScreenNumberOfScreen = _lib.XScreenNumberOfScreen XScreenNumberOfScreen.restype = c_int XScreenNumberOfScreen.argtypes = [POINTER(Screen)] XErrorHandler = CFUNCTYPE(c_int, POINTER(Display), POINTER(XErrorEvent)) # /usr/include/X11/Xlib.h:1853 # /usr/include/X11/Xlib.h:1858 XSetErrorHandler = _lib.XSetErrorHandler XSetErrorHandler.restype = XErrorHandler XSetErrorHandler.argtypes = [XErrorHandler] XIOErrorHandler = CFUNCTYPE(c_int, POINTER(Display)) # /usr/include/X11/Xlib.h:1863 # /usr/include/X11/Xlib.h:1867 XSetIOErrorHandler = _lib.XSetIOErrorHandler XSetIOErrorHandler.restype = XIOErrorHandler XSetIOErrorHandler.argtypes = [XIOErrorHandler] # /usr/include/X11/Xlib.h:1872 XListPixmapFormats = _lib.XListPixmapFormats XListPixmapFormats.restype = POINTER(XPixmapFormatValues) XListPixmapFormats.argtypes = [POINTER(Display), POINTER(c_int)] # /usr/include/X11/Xlib.h:1876 XListDepths = _lib.XListDepths XListDepths.restype = POINTER(c_int) XListDepths.argtypes = [POINTER(Display), c_int, POINTER(c_int)] # /usr/include/X11/Xlib.h:1884 XReconfigureWMWindow = _lib.XReconfigureWMWindow XReconfigureWMWindow.restype = c_int XReconfigureWMWindow.argtypes = [POINTER(Display), Window, c_int, c_uint, POINTER(XWindowChanges)] # /usr/include/X11/Xlib.h:1892 XGetWMProtocols = _lib.XGetWMProtocols XGetWMProtocols.restype = c_int XGetWMProtocols.argtypes = [POINTER(Display), Window, POINTER(POINTER(Atom)), POINTER(c_int)] # /usr/include/X11/Xlib.h:1898 XSetWMProtocols = _lib.XSetWMProtocols XSetWMProtocols.restype = c_int XSetWMProtocols.argtypes = [POINTER(Display), Window, POINTER(Atom), c_int] # /usr/include/X11/Xlib.h:1904 XIconifyWindow = _lib.XIconifyWindow XIconifyWindow.restype = c_int XIconifyWindow.argtypes = [POINTER(Display), Window, c_int] # /usr/include/X11/Xlib.h:1909 XWithdrawWindow = _lib.XWithdrawWindow XWithdrawWindow.restype = c_int XWithdrawWindow.argtypes = [POINTER(Display), Window, c_int] # /usr/include/X11/Xlib.h:1914 XGetCommand = _lib.XGetCommand XGetCommand.restype = c_int XGetCommand.argtypes = [POINTER(Display), Window, POINTER(POINTER(c_char_p)), POINTER(c_int)] # /usr/include/X11/Xlib.h:1920 XGetWMColormapWindows = _lib.XGetWMColormapWindows XGetWMColormapWindows.restype = c_int XGetWMColormapWindows.argtypes = [POINTER(Display), Window, POINTER(POINTER(Window)), POINTER(c_int)] # /usr/include/X11/Xlib.h:1926 XSetWMColormapWindows = _lib.XSetWMColormapWindows XSetWMColormapWindows.restype = c_int XSetWMColormapWindows.argtypes = [POINTER(Display), Window, POINTER(Window), c_int] # /usr/include/X11/Xlib.h:1932 XFreeStringList = _lib.XFreeStringList XFreeStringList.restype = None XFreeStringList.argtypes = [POINTER(c_char_p)] # /usr/include/X11/Xlib.h:1935 XSetTransientForHint = _lib.XSetTransientForHint XSetTransientForHint.restype = c_int XSetTransientForHint.argtypes = [POINTER(Display), Window, Window] # /usr/include/X11/Xlib.h:1943 XActivateScreenSaver = _lib.XActivateScreenSaver XActivateScreenSaver.restype = c_int XActivateScreenSaver.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1947 XAddHost = _lib.XAddHost XAddHost.restype = c_int XAddHost.argtypes = [POINTER(Display), POINTER(XHostAddress)] # /usr/include/X11/Xlib.h:1952 XAddHosts = _lib.XAddHosts XAddHosts.restype = c_int XAddHosts.argtypes = [POINTER(Display), POINTER(XHostAddress), c_int] # /usr/include/X11/Xlib.h:1958 XAddToExtensionList = _lib.XAddToExtensionList XAddToExtensionList.restype = c_int XAddToExtensionList.argtypes = [POINTER(POINTER(struct__XExtData)), POINTER(XExtData)] # /usr/include/X11/Xlib.h:1963 XAddToSaveSet = _lib.XAddToSaveSet XAddToSaveSet.restype = c_int XAddToSaveSet.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:1968 XAllocColor = _lib.XAllocColor XAllocColor.restype = c_int XAllocColor.argtypes = [POINTER(Display), Colormap, POINTER(XColor)] # /usr/include/X11/Xlib.h:1974 XAllocColorCells = _lib.XAllocColorCells XAllocColorCells.restype = c_int XAllocColorCells.argtypes = [POINTER(Display), Colormap, c_int, POINTER(c_ulong), c_uint, POINTER(c_ulong), c_uint] # /usr/include/X11/Xlib.h:1984 XAllocColorPlanes = _lib.XAllocColorPlanes XAllocColorPlanes.restype = c_int XAllocColorPlanes.argtypes = [POINTER(Display), Colormap, c_int, POINTER(c_ulong), c_int, c_int, c_int, c_int, POINTER(c_ulong), POINTER(c_ulong), POINTER(c_ulong)] # /usr/include/X11/Xlib.h:1998 XAllocNamedColor = _lib.XAllocNamedColor XAllocNamedColor.restype = c_int XAllocNamedColor.argtypes = [POINTER(Display), Colormap, c_char_p, POINTER(XColor), POINTER(XColor)] # /usr/include/X11/Xlib.h:2006 XAllowEvents = _lib.XAllowEvents XAllowEvents.restype = c_int XAllowEvents.argtypes = [POINTER(Display), c_int, Time] # /usr/include/X11/Xlib.h:2012 XAutoRepeatOff = _lib.XAutoRepeatOff XAutoRepeatOff.restype = c_int XAutoRepeatOff.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2016 XAutoRepeatOn = _lib.XAutoRepeatOn XAutoRepeatOn.restype = c_int XAutoRepeatOn.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2020 XBell = _lib.XBell XBell.restype = c_int XBell.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2025 XBitmapBitOrder = _lib.XBitmapBitOrder XBitmapBitOrder.restype = c_int XBitmapBitOrder.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2029 XBitmapPad = _lib.XBitmapPad XBitmapPad.restype = c_int XBitmapPad.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2033 XBitmapUnit = _lib.XBitmapUnit XBitmapUnit.restype = c_int XBitmapUnit.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2037 XCellsOfScreen = _lib.XCellsOfScreen XCellsOfScreen.restype = c_int XCellsOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2041 XChangeActivePointerGrab = _lib.XChangeActivePointerGrab XChangeActivePointerGrab.restype = c_int XChangeActivePointerGrab.argtypes = [POINTER(Display), c_uint, Cursor, Time] # /usr/include/X11/Xlib.h:2048 XChangeGC = _lib.XChangeGC XChangeGC.restype = c_int XChangeGC.argtypes = [POINTER(Display), GC, c_ulong, POINTER(XGCValues)] # /usr/include/X11/Xlib.h:2055 XChangeKeyboardControl = _lib.XChangeKeyboardControl XChangeKeyboardControl.restype = c_int XChangeKeyboardControl.argtypes = [POINTER(Display), c_ulong, POINTER(XKeyboardControl)] # /usr/include/X11/Xlib.h:2061 XChangeKeyboardMapping = _lib.XChangeKeyboardMapping XChangeKeyboardMapping.restype = c_int XChangeKeyboardMapping.argtypes = [POINTER(Display), c_int, c_int, POINTER(KeySym), c_int] # /usr/include/X11/Xlib.h:2069 XChangePointerControl = _lib.XChangePointerControl XChangePointerControl.restype = c_int XChangePointerControl.argtypes = [POINTER(Display), c_int, c_int, c_int, c_int, c_int] # /usr/include/X11/Xlib.h:2078 XChangeProperty = _lib.XChangeProperty XChangeProperty.restype = c_int XChangeProperty.argtypes = [POINTER(Display), Window, Atom, Atom, c_int, c_int, POINTER(c_ubyte), c_int] # /usr/include/X11/Xlib.h:2089 XChangeSaveSet = _lib.XChangeSaveSet XChangeSaveSet.restype = c_int XChangeSaveSet.argtypes = [POINTER(Display), Window, c_int] # /usr/include/X11/Xlib.h:2095 XChangeWindowAttributes = _lib.XChangeWindowAttributes XChangeWindowAttributes.restype = c_int XChangeWindowAttributes.argtypes = [POINTER(Display), Window, c_ulong, POINTER(XSetWindowAttributes)] # /usr/include/X11/Xlib.h:2102 XCheckIfEvent = _lib.XCheckIfEvent XCheckIfEvent.restype = c_int XCheckIfEvent.argtypes = [POINTER(Display), POINTER(XEvent), CFUNCTYPE(c_int, POINTER(Display), POINTER(XEvent), XPointer), XPointer] # /usr/include/X11/Xlib.h:2113 XCheckMaskEvent = _lib.XCheckMaskEvent XCheckMaskEvent.restype = c_int XCheckMaskEvent.argtypes = [POINTER(Display), c_long, POINTER(XEvent)] # /usr/include/X11/Xlib.h:2119 XCheckTypedEvent = _lib.XCheckTypedEvent XCheckTypedEvent.restype = c_int XCheckTypedEvent.argtypes = [POINTER(Display), c_int, POINTER(XEvent)] # /usr/include/X11/Xlib.h:2125 XCheckTypedWindowEvent = _lib.XCheckTypedWindowEvent XCheckTypedWindowEvent.restype = c_int XCheckTypedWindowEvent.argtypes = [POINTER(Display), Window, c_int, POINTER(XEvent)] # /usr/include/X11/Xlib.h:2132 XCheckWindowEvent = _lib.XCheckWindowEvent XCheckWindowEvent.restype = c_int XCheckWindowEvent.argtypes = [POINTER(Display), Window, c_long, POINTER(XEvent)] # /usr/include/X11/Xlib.h:2139 XCirculateSubwindows = _lib.XCirculateSubwindows XCirculateSubwindows.restype = c_int XCirculateSubwindows.argtypes = [POINTER(Display), Window, c_int] # /usr/include/X11/Xlib.h:2145 XCirculateSubwindowsDown = _lib.XCirculateSubwindowsDown XCirculateSubwindowsDown.restype = c_int XCirculateSubwindowsDown.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2150 XCirculateSubwindowsUp = _lib.XCirculateSubwindowsUp XCirculateSubwindowsUp.restype = c_int XCirculateSubwindowsUp.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2155 XClearArea = _lib.XClearArea XClearArea.restype = c_int XClearArea.argtypes = [POINTER(Display), Window, c_int, c_int, c_uint, c_uint, c_int] # /usr/include/X11/Xlib.h:2165 XClearWindow = _lib.XClearWindow XClearWindow.restype = c_int XClearWindow.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2170 XCloseDisplay = _lib.XCloseDisplay XCloseDisplay.restype = c_int XCloseDisplay.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2174 XConfigureWindow = _lib.XConfigureWindow XConfigureWindow.restype = c_int XConfigureWindow.argtypes = [POINTER(Display), Window, c_uint, POINTER(XWindowChanges)] # /usr/include/X11/Xlib.h:2181 XConnectionNumber = _lib.XConnectionNumber XConnectionNumber.restype = c_int XConnectionNumber.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2185 XConvertSelection = _lib.XConvertSelection XConvertSelection.restype = c_int XConvertSelection.argtypes = [POINTER(Display), Atom, Atom, Atom, Window, Time] # /usr/include/X11/Xlib.h:2194 XCopyArea = _lib.XCopyArea XCopyArea.restype = c_int XCopyArea.argtypes = [POINTER(Display), Drawable, Drawable, GC, c_int, c_int, c_uint, c_uint, c_int, c_int] # /usr/include/X11/Xlib.h:2207 XCopyGC = _lib.XCopyGC XCopyGC.restype = c_int XCopyGC.argtypes = [POINTER(Display), GC, c_ulong, GC] # /usr/include/X11/Xlib.h:2214 XCopyPlane = _lib.XCopyPlane XCopyPlane.restype = c_int XCopyPlane.argtypes = [POINTER(Display), Drawable, Drawable, GC, c_int, c_int, c_uint, c_uint, c_int, c_int, c_ulong] # /usr/include/X11/Xlib.h:2228 XDefaultDepth = _lib.XDefaultDepth XDefaultDepth.restype = c_int XDefaultDepth.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2233 XDefaultDepthOfScreen = _lib.XDefaultDepthOfScreen XDefaultDepthOfScreen.restype = c_int XDefaultDepthOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2237 XDefaultScreen = _lib.XDefaultScreen XDefaultScreen.restype = c_int XDefaultScreen.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2241 XDefineCursor = _lib.XDefineCursor XDefineCursor.restype = c_int XDefineCursor.argtypes = [POINTER(Display), Window, Cursor] # /usr/include/X11/Xlib.h:2247 XDeleteProperty = _lib.XDeleteProperty XDeleteProperty.restype = c_int XDeleteProperty.argtypes = [POINTER(Display), Window, Atom] # /usr/include/X11/Xlib.h:2253 XDestroyWindow = _lib.XDestroyWindow XDestroyWindow.restype = c_int XDestroyWindow.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2258 XDestroySubwindows = _lib.XDestroySubwindows XDestroySubwindows.restype = c_int XDestroySubwindows.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2263 XDoesBackingStore = _lib.XDoesBackingStore XDoesBackingStore.restype = c_int XDoesBackingStore.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2267 XDoesSaveUnders = _lib.XDoesSaveUnders XDoesSaveUnders.restype = c_int XDoesSaveUnders.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2271 XDisableAccessControl = _lib.XDisableAccessControl XDisableAccessControl.restype = c_int XDisableAccessControl.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2276 XDisplayCells = _lib.XDisplayCells XDisplayCells.restype = c_int XDisplayCells.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2281 XDisplayHeight = _lib.XDisplayHeight XDisplayHeight.restype = c_int XDisplayHeight.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2286 XDisplayHeightMM = _lib.XDisplayHeightMM XDisplayHeightMM.restype = c_int XDisplayHeightMM.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2291 XDisplayKeycodes = _lib.XDisplayKeycodes XDisplayKeycodes.restype = c_int XDisplayKeycodes.argtypes = [POINTER(Display), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xlib.h:2297 XDisplayPlanes = _lib.XDisplayPlanes XDisplayPlanes.restype = c_int XDisplayPlanes.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2302 XDisplayWidth = _lib.XDisplayWidth XDisplayWidth.restype = c_int XDisplayWidth.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2307 XDisplayWidthMM = _lib.XDisplayWidthMM XDisplayWidthMM.restype = c_int XDisplayWidthMM.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2312 XDrawArc = _lib.XDrawArc XDrawArc.restype = c_int XDrawArc.argtypes = [POINTER(Display), Drawable, GC, c_int, c_int, c_uint, c_uint, c_int, c_int] # /usr/include/X11/Xlib.h:2324 XDrawArcs = _lib.XDrawArcs XDrawArcs.restype = c_int XDrawArcs.argtypes = [POINTER(Display), Drawable, GC, POINTER(XArc), c_int] # /usr/include/X11/Xlib.h:2332 XDrawImageString = _lib.XDrawImageString XDrawImageString.restype = c_int XDrawImageString.argtypes = [POINTER(Display), Drawable, GC, c_int, c_int, c_char_p, c_int] # /usr/include/X11/Xlib.h:2342 XDrawImageString16 = _lib.XDrawImageString16 XDrawImageString16.restype = c_int XDrawImageString16.argtypes = [POINTER(Display), Drawable, GC, c_int, c_int, POINTER(XChar2b), c_int] # /usr/include/X11/Xlib.h:2352 XDrawLine = _lib.XDrawLine XDrawLine.restype = c_int XDrawLine.argtypes = [POINTER(Display), Drawable, GC, c_int, c_int, c_int, c_int] # /usr/include/X11/Xlib.h:2362 XDrawLines = _lib.XDrawLines XDrawLines.restype = c_int XDrawLines.argtypes = [POINTER(Display), Drawable, GC, POINTER(XPoint), c_int, c_int] # /usr/include/X11/Xlib.h:2371 XDrawPoint = _lib.XDrawPoint XDrawPoint.restype = c_int XDrawPoint.argtypes = [POINTER(Display), Drawable, GC, c_int, c_int] # /usr/include/X11/Xlib.h:2379 XDrawPoints = _lib.XDrawPoints XDrawPoints.restype = c_int XDrawPoints.argtypes = [POINTER(Display), Drawable, GC, POINTER(XPoint), c_int, c_int] # /usr/include/X11/Xlib.h:2388 XDrawRectangle = _lib.XDrawRectangle XDrawRectangle.restype = c_int XDrawRectangle.argtypes = [POINTER(Display), Drawable, GC, c_int, c_int, c_uint, c_uint] # /usr/include/X11/Xlib.h:2398 XDrawRectangles = _lib.XDrawRectangles XDrawRectangles.restype = c_int XDrawRectangles.argtypes = [POINTER(Display), Drawable, GC, POINTER(XRectangle), c_int] # /usr/include/X11/Xlib.h:2406 XDrawSegments = _lib.XDrawSegments XDrawSegments.restype = c_int XDrawSegments.argtypes = [POINTER(Display), Drawable, GC, POINTER(XSegment), c_int] # /usr/include/X11/Xlib.h:2414 XDrawString = _lib.XDrawString XDrawString.restype = c_int XDrawString.argtypes = [POINTER(Display), Drawable, GC, c_int, c_int, c_char_p, c_int] # /usr/include/X11/Xlib.h:2424 XDrawString16 = _lib.XDrawString16 XDrawString16.restype = c_int XDrawString16.argtypes = [POINTER(Display), Drawable, GC, c_int, c_int, POINTER(XChar2b), c_int] # /usr/include/X11/Xlib.h:2434 XDrawText = _lib.XDrawText XDrawText.restype = c_int XDrawText.argtypes = [POINTER(Display), Drawable, GC, c_int, c_int, POINTER(XTextItem), c_int] # /usr/include/X11/Xlib.h:2444 XDrawText16 = _lib.XDrawText16 XDrawText16.restype = c_int XDrawText16.argtypes = [POINTER(Display), Drawable, GC, c_int, c_int, POINTER(XTextItem16), c_int] # /usr/include/X11/Xlib.h:2454 XEnableAccessControl = _lib.XEnableAccessControl XEnableAccessControl.restype = c_int XEnableAccessControl.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2458 XEventsQueued = _lib.XEventsQueued XEventsQueued.restype = c_int XEventsQueued.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2463 XFetchName = _lib.XFetchName XFetchName.restype = c_int XFetchName.argtypes = [POINTER(Display), Window, POINTER(c_char_p)] # /usr/include/X11/Xlib.h:2469 XFillArc = _lib.XFillArc XFillArc.restype = c_int XFillArc.argtypes = [POINTER(Display), Drawable, GC, c_int, c_int, c_uint, c_uint, c_int, c_int] # /usr/include/X11/Xlib.h:2481 XFillArcs = _lib.XFillArcs XFillArcs.restype = c_int XFillArcs.argtypes = [POINTER(Display), Drawable, GC, POINTER(XArc), c_int] # /usr/include/X11/Xlib.h:2489 XFillPolygon = _lib.XFillPolygon XFillPolygon.restype = c_int XFillPolygon.argtypes = [POINTER(Display), Drawable, GC, POINTER(XPoint), c_int, c_int, c_int] # /usr/include/X11/Xlib.h:2499 XFillRectangle = _lib.XFillRectangle XFillRectangle.restype = c_int XFillRectangle.argtypes = [POINTER(Display), Drawable, GC, c_int, c_int, c_uint, c_uint] # /usr/include/X11/Xlib.h:2509 XFillRectangles = _lib.XFillRectangles XFillRectangles.restype = c_int XFillRectangles.argtypes = [POINTER(Display), Drawable, GC, POINTER(XRectangle), c_int] # /usr/include/X11/Xlib.h:2517 XFlush = _lib.XFlush XFlush.restype = c_int XFlush.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2521 XForceScreenSaver = _lib.XForceScreenSaver XForceScreenSaver.restype = c_int XForceScreenSaver.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2526 XFree = _lib.XFree XFree.restype = c_int XFree.argtypes = [POINTER(None)] # /usr/include/X11/Xlib.h:2530 XFreeColormap = _lib.XFreeColormap XFreeColormap.restype = c_int XFreeColormap.argtypes = [POINTER(Display), Colormap] # /usr/include/X11/Xlib.h:2535 XFreeColors = _lib.XFreeColors XFreeColors.restype = c_int XFreeColors.argtypes = [POINTER(Display), Colormap, POINTER(c_ulong), c_int, c_ulong] # /usr/include/X11/Xlib.h:2543 XFreeCursor = _lib.XFreeCursor XFreeCursor.restype = c_int XFreeCursor.argtypes = [POINTER(Display), Cursor] # /usr/include/X11/Xlib.h:2548 XFreeExtensionList = _lib.XFreeExtensionList XFreeExtensionList.restype = c_int XFreeExtensionList.argtypes = [POINTER(c_char_p)] # /usr/include/X11/Xlib.h:2552 XFreeFont = _lib.XFreeFont XFreeFont.restype = c_int XFreeFont.argtypes = [POINTER(Display), POINTER(XFontStruct)] # /usr/include/X11/Xlib.h:2557 XFreeFontInfo = _lib.XFreeFontInfo XFreeFontInfo.restype = c_int XFreeFontInfo.argtypes = [POINTER(c_char_p), POINTER(XFontStruct), c_int] # /usr/include/X11/Xlib.h:2563 XFreeFontNames = _lib.XFreeFontNames XFreeFontNames.restype = c_int XFreeFontNames.argtypes = [POINTER(c_char_p)] # /usr/include/X11/Xlib.h:2567 XFreeFontPath = _lib.XFreeFontPath XFreeFontPath.restype = c_int XFreeFontPath.argtypes = [POINTER(c_char_p)] # /usr/include/X11/Xlib.h:2571 XFreeGC = _lib.XFreeGC XFreeGC.restype = c_int XFreeGC.argtypes = [POINTER(Display), GC] # /usr/include/X11/Xlib.h:2576 XFreeModifiermap = _lib.XFreeModifiermap XFreeModifiermap.restype = c_int XFreeModifiermap.argtypes = [POINTER(XModifierKeymap)] # /usr/include/X11/Xlib.h:2580 XFreePixmap = _lib.XFreePixmap XFreePixmap.restype = c_int XFreePixmap.argtypes = [POINTER(Display), Pixmap] # /usr/include/X11/Xlib.h:2585 XGeometry = _lib.XGeometry XGeometry.restype = c_int XGeometry.argtypes = [POINTER(Display), c_int, c_char_p, c_char_p, c_uint, c_uint, c_uint, c_int, c_int, POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xlib.h:2601 XGetErrorDatabaseText = _lib.XGetErrorDatabaseText XGetErrorDatabaseText.restype = c_int XGetErrorDatabaseText.argtypes = [POINTER(Display), c_char_p, c_char_p, c_char_p, c_char_p, c_int] # /usr/include/X11/Xlib.h:2610 XGetErrorText = _lib.XGetErrorText XGetErrorText.restype = c_int XGetErrorText.argtypes = [POINTER(Display), c_int, c_char_p, c_int] # /usr/include/X11/Xlib.h:2617 XGetFontProperty = _lib.XGetFontProperty XGetFontProperty.restype = c_int XGetFontProperty.argtypes = [POINTER(XFontStruct), Atom, POINTER(c_ulong)] # /usr/include/X11/Xlib.h:2623 XGetGCValues = _lib.XGetGCValues XGetGCValues.restype = c_int XGetGCValues.argtypes = [POINTER(Display), GC, c_ulong, POINTER(XGCValues)] # /usr/include/X11/Xlib.h:2630 XGetGeometry = _lib.XGetGeometry XGetGeometry.restype = c_int XGetGeometry.argtypes = [POINTER(Display), Drawable, POINTER(Window), POINTER(c_int), POINTER(c_int), POINTER(c_uint), POINTER(c_uint), POINTER(c_uint), POINTER(c_uint)] # /usr/include/X11/Xlib.h:2642 XGetIconName = _lib.XGetIconName XGetIconName.restype = c_int XGetIconName.argtypes = [POINTER(Display), Window, POINTER(c_char_p)] # /usr/include/X11/Xlib.h:2648 XGetInputFocus = _lib.XGetInputFocus XGetInputFocus.restype = c_int XGetInputFocus.argtypes = [POINTER(Display), POINTER(Window), POINTER(c_int)] # /usr/include/X11/Xlib.h:2654 XGetKeyboardControl = _lib.XGetKeyboardControl XGetKeyboardControl.restype = c_int XGetKeyboardControl.argtypes = [POINTER(Display), POINTER(XKeyboardState)] # /usr/include/X11/Xlib.h:2659 XGetPointerControl = _lib.XGetPointerControl XGetPointerControl.restype = c_int XGetPointerControl.argtypes = [POINTER(Display), POINTER(c_int), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xlib.h:2666 XGetPointerMapping = _lib.XGetPointerMapping XGetPointerMapping.restype = c_int XGetPointerMapping.argtypes = [POINTER(Display), POINTER(c_ubyte), c_int] # /usr/include/X11/Xlib.h:2672 XGetScreenSaver = _lib.XGetScreenSaver XGetScreenSaver.restype = c_int XGetScreenSaver.argtypes = [POINTER(Display), POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xlib.h:2680 XGetTransientForHint = _lib.XGetTransientForHint XGetTransientForHint.restype = c_int XGetTransientForHint.argtypes = [POINTER(Display), Window, POINTER(Window)] # /usr/include/X11/Xlib.h:2686 XGetWindowProperty = _lib.XGetWindowProperty XGetWindowProperty.restype = c_int XGetWindowProperty.argtypes = [POINTER(Display), Window, Atom, c_long, c_long, c_int, Atom, POINTER(Atom), POINTER(c_int), POINTER(c_ulong), POINTER(c_ulong), POINTER(POINTER(c_ubyte))] # /usr/include/X11/Xlib.h:2701 XGetWindowAttributes = _lib.XGetWindowAttributes XGetWindowAttributes.restype = c_int XGetWindowAttributes.argtypes = [POINTER(Display), Window, POINTER(XWindowAttributes)] # /usr/include/X11/Xlib.h:2707 XGrabButton = _lib.XGrabButton XGrabButton.restype = c_int XGrabButton.argtypes = [POINTER(Display), c_uint, c_uint, Window, c_int, c_uint, c_int, c_int, Window, Cursor] # /usr/include/X11/Xlib.h:2720 XGrabKey = _lib.XGrabKey XGrabKey.restype = c_int XGrabKey.argtypes = [POINTER(Display), c_int, c_uint, Window, c_int, c_int, c_int] # /usr/include/X11/Xlib.h:2730 XGrabKeyboard = _lib.XGrabKeyboard XGrabKeyboard.restype = c_int XGrabKeyboard.argtypes = [POINTER(Display), Window, c_int, c_int, c_int, Time] # /usr/include/X11/Xlib.h:2739 XGrabPointer = _lib.XGrabPointer XGrabPointer.restype = c_int XGrabPointer.argtypes = [POINTER(Display), Window, c_int, c_uint, c_int, c_int, Window, Cursor, Time] # /usr/include/X11/Xlib.h:2751 XGrabServer = _lib.XGrabServer XGrabServer.restype = c_int XGrabServer.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2755 XHeightMMOfScreen = _lib.XHeightMMOfScreen XHeightMMOfScreen.restype = c_int XHeightMMOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2759 XHeightOfScreen = _lib.XHeightOfScreen XHeightOfScreen.restype = c_int XHeightOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2763 XIfEvent = _lib.XIfEvent XIfEvent.restype = c_int XIfEvent.argtypes = [POINTER(Display), POINTER(XEvent), CFUNCTYPE(c_int, POINTER(Display), POINTER(XEvent), XPointer), XPointer] # /usr/include/X11/Xlib.h:2774 XImageByteOrder = _lib.XImageByteOrder XImageByteOrder.restype = c_int XImageByteOrder.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2778 XInstallColormap = _lib.XInstallColormap XInstallColormap.restype = c_int XInstallColormap.argtypes = [POINTER(Display), Colormap] # /usr/include/X11/Xlib.h:2783 XKeysymToKeycode = _lib.XKeysymToKeycode XKeysymToKeycode.restype = KeyCode XKeysymToKeycode.argtypes = [POINTER(Display), KeySym] # /usr/include/X11/Xlib.h:2788 XKillClient = _lib.XKillClient XKillClient.restype = c_int XKillClient.argtypes = [POINTER(Display), XID] # /usr/include/X11/Xlib.h:2793 XLookupColor = _lib.XLookupColor XLookupColor.restype = c_int XLookupColor.argtypes = [POINTER(Display), Colormap, c_char_p, POINTER(XColor), POINTER(XColor)] # /usr/include/X11/Xlib.h:2801 XLowerWindow = _lib.XLowerWindow XLowerWindow.restype = c_int XLowerWindow.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2806 XMapRaised = _lib.XMapRaised XMapRaised.restype = c_int XMapRaised.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2811 XMapSubwindows = _lib.XMapSubwindows XMapSubwindows.restype = c_int XMapSubwindows.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2816 XMapWindow = _lib.XMapWindow XMapWindow.restype = c_int XMapWindow.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2821 XMaskEvent = _lib.XMaskEvent XMaskEvent.restype = c_int XMaskEvent.argtypes = [POINTER(Display), c_long, POINTER(XEvent)] # /usr/include/X11/Xlib.h:2827 XMaxCmapsOfScreen = _lib.XMaxCmapsOfScreen XMaxCmapsOfScreen.restype = c_int XMaxCmapsOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2831 XMinCmapsOfScreen = _lib.XMinCmapsOfScreen XMinCmapsOfScreen.restype = c_int XMinCmapsOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2835 XMoveResizeWindow = _lib.XMoveResizeWindow XMoveResizeWindow.restype = c_int XMoveResizeWindow.argtypes = [POINTER(Display), Window, c_int, c_int, c_uint, c_uint] # /usr/include/X11/Xlib.h:2844 XMoveWindow = _lib.XMoveWindow XMoveWindow.restype = c_int XMoveWindow.argtypes = [POINTER(Display), Window, c_int, c_int] # /usr/include/X11/Xlib.h:2851 XNextEvent = _lib.XNextEvent XNextEvent.restype = c_int XNextEvent.argtypes = [POINTER(Display), POINTER(XEvent)] # /usr/include/X11/Xlib.h:2856 XNoOp = _lib.XNoOp XNoOp.restype = c_int XNoOp.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2860 XParseColor = _lib.XParseColor XParseColor.restype = c_int XParseColor.argtypes = [POINTER(Display), Colormap, c_char_p, POINTER(XColor)] # /usr/include/X11/Xlib.h:2867 XParseGeometry = _lib.XParseGeometry XParseGeometry.restype = c_int XParseGeometry.argtypes = [c_char_p, POINTER(c_int), POINTER(c_int), POINTER(c_uint), POINTER(c_uint)] # /usr/include/X11/Xlib.h:2875 XPeekEvent = _lib.XPeekEvent XPeekEvent.restype = c_int XPeekEvent.argtypes = [POINTER(Display), POINTER(XEvent)] # /usr/include/X11/Xlib.h:2880 XPeekIfEvent = _lib.XPeekIfEvent XPeekIfEvent.restype = c_int XPeekIfEvent.argtypes = [POINTER(Display), POINTER(XEvent), CFUNCTYPE(c_int, POINTER(Display), POINTER(XEvent), XPointer), XPointer] # /usr/include/X11/Xlib.h:2891 XPending = _lib.XPending XPending.restype = c_int XPending.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2895 XPlanesOfScreen = _lib.XPlanesOfScreen XPlanesOfScreen.restype = c_int XPlanesOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2899 XProtocolRevision = _lib.XProtocolRevision XProtocolRevision.restype = c_int XProtocolRevision.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2903 XProtocolVersion = _lib.XProtocolVersion XProtocolVersion.restype = c_int XProtocolVersion.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2908 XPutBackEvent = _lib.XPutBackEvent XPutBackEvent.restype = c_int XPutBackEvent.argtypes = [POINTER(Display), POINTER(XEvent)] # /usr/include/X11/Xlib.h:2913 XPutImage = _lib.XPutImage XPutImage.restype = c_int XPutImage.argtypes = [POINTER(Display), Drawable, GC, POINTER(XImage), c_int, c_int, c_int, c_int, c_uint, c_uint] # /usr/include/X11/Xlib.h:2926 XQLength = _lib.XQLength XQLength.restype = c_int XQLength.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2930 XQueryBestCursor = _lib.XQueryBestCursor XQueryBestCursor.restype = c_int XQueryBestCursor.argtypes = [POINTER(Display), Drawable, c_uint, c_uint, POINTER(c_uint), POINTER(c_uint)] # /usr/include/X11/Xlib.h:2939 XQueryBestSize = _lib.XQueryBestSize XQueryBestSize.restype = c_int XQueryBestSize.argtypes = [POINTER(Display), c_int, Drawable, c_uint, c_uint, POINTER(c_uint), POINTER(c_uint)] # /usr/include/X11/Xlib.h:2949 XQueryBestStipple = _lib.XQueryBestStipple XQueryBestStipple.restype = c_int XQueryBestStipple.argtypes = [POINTER(Display), Drawable, c_uint, c_uint, POINTER(c_uint), POINTER(c_uint)] # /usr/include/X11/Xlib.h:2958 XQueryBestTile = _lib.XQueryBestTile XQueryBestTile.restype = c_int XQueryBestTile.argtypes = [POINTER(Display), Drawable, c_uint, c_uint, POINTER(c_uint), POINTER(c_uint)] # /usr/include/X11/Xlib.h:2967 XQueryColor = _lib.XQueryColor XQueryColor.restype = c_int XQueryColor.argtypes = [POINTER(Display), Colormap, POINTER(XColor)] # /usr/include/X11/Xlib.h:2973 XQueryColors = _lib.XQueryColors XQueryColors.restype = c_int XQueryColors.argtypes = [POINTER(Display), Colormap, POINTER(XColor), c_int] # /usr/include/X11/Xlib.h:2980 XQueryExtension = _lib.XQueryExtension XQueryExtension.restype = c_int XQueryExtension.argtypes = [POINTER(Display), c_char_p, POINTER(c_int), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xlib.h:2988 XQueryKeymap = _lib.XQueryKeymap XQueryKeymap.restype = c_int XQueryKeymap.argtypes = [POINTER(Display), c_char * 32] # /usr/include/X11/Xlib.h:2993 XQueryPointer = _lib.XQueryPointer XQueryPointer.restype = c_int XQueryPointer.argtypes = [POINTER(Display), Window, POINTER(Window), POINTER(Window), POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_uint)] # /usr/include/X11/Xlib.h:3005 XQueryTextExtents = _lib.XQueryTextExtents XQueryTextExtents.restype = c_int XQueryTextExtents.argtypes = [POINTER(Display), XID, c_char_p, c_int, POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(XCharStruct)] # /usr/include/X11/Xlib.h:3016 XQueryTextExtents16 = _lib.XQueryTextExtents16 XQueryTextExtents16.restype = c_int XQueryTextExtents16.argtypes = [POINTER(Display), XID, POINTER(XChar2b), c_int, POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(XCharStruct)] # /usr/include/X11/Xlib.h:3027 XQueryTree = _lib.XQueryTree XQueryTree.restype = c_int XQueryTree.argtypes = [POINTER(Display), Window, POINTER(Window), POINTER(Window), POINTER(POINTER(Window)), POINTER(c_uint)] # /usr/include/X11/Xlib.h:3036 XRaiseWindow = _lib.XRaiseWindow XRaiseWindow.restype = c_int XRaiseWindow.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:3041 XReadBitmapFile = _lib.XReadBitmapFile XReadBitmapFile.restype = c_int XReadBitmapFile.argtypes = [POINTER(Display), Drawable, c_char_p, POINTER(c_uint), POINTER(c_uint), POINTER(Pixmap), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xlib.h:3052 XReadBitmapFileData = _lib.XReadBitmapFileData XReadBitmapFileData.restype = c_int XReadBitmapFileData.argtypes = [c_char_p, POINTER(c_uint), POINTER(c_uint), POINTER(POINTER(c_ubyte)), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xlib.h:3061 XRebindKeysym = _lib.XRebindKeysym XRebindKeysym.restype = c_int XRebindKeysym.argtypes = [POINTER(Display), KeySym, POINTER(KeySym), c_int, POINTER(c_ubyte), c_int] # /usr/include/X11/Xlib.h:3070 XRecolorCursor = _lib.XRecolorCursor XRecolorCursor.restype = c_int XRecolorCursor.argtypes = [POINTER(Display), Cursor, POINTER(XColor), POINTER(XColor)] # /usr/include/X11/Xlib.h:3077 XRefreshKeyboardMapping = _lib.XRefreshKeyboardMapping XRefreshKeyboardMapping.restype = c_int XRefreshKeyboardMapping.argtypes = [POINTER(XMappingEvent)] # /usr/include/X11/Xlib.h:3081 XRemoveFromSaveSet = _lib.XRemoveFromSaveSet XRemoveFromSaveSet.restype = c_int XRemoveFromSaveSet.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:3086 XRemoveHost = _lib.XRemoveHost XRemoveHost.restype = c_int XRemoveHost.argtypes = [POINTER(Display), POINTER(XHostAddress)] # /usr/include/X11/Xlib.h:3091 XRemoveHosts = _lib.XRemoveHosts XRemoveHosts.restype = c_int XRemoveHosts.argtypes = [POINTER(Display), POINTER(XHostAddress), c_int] # /usr/include/X11/Xlib.h:3097 XReparentWindow = _lib.XReparentWindow XReparentWindow.restype = c_int XReparentWindow.argtypes = [POINTER(Display), Window, Window, c_int, c_int] # /usr/include/X11/Xlib.h:3105 XResetScreenSaver = _lib.XResetScreenSaver XResetScreenSaver.restype = c_int XResetScreenSaver.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:3109 XResizeWindow = _lib.XResizeWindow XResizeWindow.restype = c_int XResizeWindow.argtypes = [POINTER(Display), Window, c_uint, c_uint] # /usr/include/X11/Xlib.h:3116 XRestackWindows = _lib.XRestackWindows XRestackWindows.restype = c_int XRestackWindows.argtypes = [POINTER(Display), POINTER(Window), c_int] # /usr/include/X11/Xlib.h:3122 XRotateBuffers = _lib.XRotateBuffers XRotateBuffers.restype = c_int XRotateBuffers.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:3127 XRotateWindowProperties = _lib.XRotateWindowProperties XRotateWindowProperties.restype = c_int XRotateWindowProperties.argtypes = [POINTER(Display), Window, POINTER(Atom), c_int, c_int] # /usr/include/X11/Xlib.h:3135 XScreenCount = _lib.XScreenCount XScreenCount.restype = c_int XScreenCount.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:3139 XSelectInput = _lib.XSelectInput XSelectInput.restype = c_int XSelectInput.argtypes = [POINTER(Display), Window, c_long] # /usr/include/X11/Xlib.h:3145 XSendEvent = _lib.XSendEvent XSendEvent.restype = c_int XSendEvent.argtypes = [POINTER(Display), Window, c_int, c_long, POINTER(XEvent)] # /usr/include/X11/Xlib.h:3153 XSetAccessControl = _lib.XSetAccessControl XSetAccessControl.restype = c_int XSetAccessControl.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:3158 XSetArcMode = _lib.XSetArcMode XSetArcMode.restype = c_int XSetArcMode.argtypes = [POINTER(Display), GC, c_int] # /usr/include/X11/Xlib.h:3164 XSetBackground = _lib.XSetBackground XSetBackground.restype = c_int XSetBackground.argtypes = [POINTER(Display), GC, c_ulong] # /usr/include/X11/Xlib.h:3170 XSetClipMask = _lib.XSetClipMask XSetClipMask.restype = c_int XSetClipMask.argtypes = [POINTER(Display), GC, Pixmap] # /usr/include/X11/Xlib.h:3176 XSetClipOrigin = _lib.XSetClipOrigin XSetClipOrigin.restype = c_int XSetClipOrigin.argtypes = [POINTER(Display), GC, c_int, c_int] # /usr/include/X11/Xlib.h:3183 XSetClipRectangles = _lib.XSetClipRectangles XSetClipRectangles.restype = c_int XSetClipRectangles.argtypes = [POINTER(Display), GC, c_int, c_int, POINTER(XRectangle), c_int, c_int] # /usr/include/X11/Xlib.h:3193 XSetCloseDownMode = _lib.XSetCloseDownMode XSetCloseDownMode.restype = c_int XSetCloseDownMode.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:3198 XSetCommand = _lib.XSetCommand XSetCommand.restype = c_int XSetCommand.argtypes = [POINTER(Display), Window, POINTER(c_char_p), c_int] # /usr/include/X11/Xlib.h:3205 XSetDashes = _lib.XSetDashes XSetDashes.restype = c_int XSetDashes.argtypes = [POINTER(Display), GC, c_int, c_char_p, c_int] # /usr/include/X11/Xlib.h:3213 XSetFillRule = _lib.XSetFillRule XSetFillRule.restype = c_int XSetFillRule.argtypes = [POINTER(Display), GC, c_int] # /usr/include/X11/Xlib.h:3219 XSetFillStyle = _lib.XSetFillStyle XSetFillStyle.restype = c_int XSetFillStyle.argtypes = [POINTER(Display), GC, c_int] # /usr/include/X11/Xlib.h:3225 XSetFont = _lib.XSetFont XSetFont.restype = c_int XSetFont.argtypes = [POINTER(Display), GC, Font] # /usr/include/X11/Xlib.h:3231 XSetFontPath = _lib.XSetFontPath XSetFontPath.restype = c_int XSetFontPath.argtypes = [POINTER(Display), POINTER(c_char_p), c_int] # /usr/include/X11/Xlib.h:3237 XSetForeground = _lib.XSetForeground XSetForeground.restype = c_int XSetForeground.argtypes = [POINTER(Display), GC, c_ulong] # /usr/include/X11/Xlib.h:3243 XSetFunction = _lib.XSetFunction XSetFunction.restype = c_int XSetFunction.argtypes = [POINTER(Display), GC, c_int] # /usr/include/X11/Xlib.h:3249 XSetGraphicsExposures = _lib.XSetGraphicsExposures XSetGraphicsExposures.restype = c_int XSetGraphicsExposures.argtypes = [POINTER(Display), GC, c_int] # /usr/include/X11/Xlib.h:3255 XSetIconName = _lib.XSetIconName XSetIconName.restype = c_int XSetIconName.argtypes = [POINTER(Display), Window, c_char_p] # /usr/include/X11/Xlib.h:3261 XSetInputFocus = _lib.XSetInputFocus XSetInputFocus.restype = c_int XSetInputFocus.argtypes = [POINTER(Display), Window, c_int, Time] # /usr/include/X11/Xlib.h:3268 XSetLineAttributes = _lib.XSetLineAttributes XSetLineAttributes.restype = c_int XSetLineAttributes.argtypes = [POINTER(Display), GC, c_uint, c_int, c_int, c_int] # /usr/include/X11/Xlib.h:3277 XSetModifierMapping = _lib.XSetModifierMapping XSetModifierMapping.restype = c_int XSetModifierMapping.argtypes = [POINTER(Display), POINTER(XModifierKeymap)] # /usr/include/X11/Xlib.h:3282 XSetPlaneMask = _lib.XSetPlaneMask XSetPlaneMask.restype = c_int XSetPlaneMask.argtypes = [POINTER(Display), GC, c_ulong] # /usr/include/X11/Xlib.h:3288 XSetPointerMapping = _lib.XSetPointerMapping XSetPointerMapping.restype = c_int XSetPointerMapping.argtypes = [POINTER(Display), POINTER(c_ubyte), c_int] # /usr/include/X11/Xlib.h:3294 XSetScreenSaver = _lib.XSetScreenSaver XSetScreenSaver.restype = c_int XSetScreenSaver.argtypes = [POINTER(Display), c_int, c_int, c_int, c_int] # /usr/include/X11/Xlib.h:3302 XSetSelectionOwner = _lib.XSetSelectionOwner XSetSelectionOwner.restype = c_int XSetSelectionOwner.argtypes = [POINTER(Display), Atom, Window, Time] # /usr/include/X11/Xlib.h:3309 XSetState = _lib.XSetState XSetState.restype = c_int XSetState.argtypes = [POINTER(Display), GC, c_ulong, c_ulong, c_int, c_ulong] # /usr/include/X11/Xlib.h:3318 XSetStipple = _lib.XSetStipple XSetStipple.restype = c_int XSetStipple.argtypes = [POINTER(Display), GC, Pixmap] # /usr/include/X11/Xlib.h:3324 XSetSubwindowMode = _lib.XSetSubwindowMode XSetSubwindowMode.restype = c_int XSetSubwindowMode.argtypes = [POINTER(Display), GC, c_int] # /usr/include/X11/Xlib.h:3330 XSetTSOrigin = _lib.XSetTSOrigin XSetTSOrigin.restype = c_int XSetTSOrigin.argtypes = [POINTER(Display), GC, c_int, c_int] # /usr/include/X11/Xlib.h:3337 XSetTile = _lib.XSetTile XSetTile.restype = c_int XSetTile.argtypes = [POINTER(Display), GC, Pixmap] # /usr/include/X11/Xlib.h:3343 XSetWindowBackground = _lib.XSetWindowBackground XSetWindowBackground.restype = c_int XSetWindowBackground.argtypes = [POINTER(Display), Window, c_ulong] # /usr/include/X11/Xlib.h:3349 XSetWindowBackgroundPixmap = _lib.XSetWindowBackgroundPixmap XSetWindowBackgroundPixmap.restype = c_int XSetWindowBackgroundPixmap.argtypes = [POINTER(Display), Window, Pixmap] # /usr/include/X11/Xlib.h:3355 XSetWindowBorder = _lib.XSetWindowBorder XSetWindowBorder.restype = c_int XSetWindowBorder.argtypes = [POINTER(Display), Window, c_ulong] # /usr/include/X11/Xlib.h:3361 XSetWindowBorderPixmap = _lib.XSetWindowBorderPixmap XSetWindowBorderPixmap.restype = c_int XSetWindowBorderPixmap.argtypes = [POINTER(Display), Window, Pixmap] # /usr/include/X11/Xlib.h:3367 XSetWindowBorderWidth = _lib.XSetWindowBorderWidth XSetWindowBorderWidth.restype = c_int XSetWindowBorderWidth.argtypes = [POINTER(Display), Window, c_uint] # /usr/include/X11/Xlib.h:3373 XSetWindowColormap = _lib.XSetWindowColormap XSetWindowColormap.restype = c_int XSetWindowColormap.argtypes = [POINTER(Display), Window, Colormap] # /usr/include/X11/Xlib.h:3379 XStoreBuffer = _lib.XStoreBuffer XStoreBuffer.restype = c_int XStoreBuffer.argtypes = [POINTER(Display), c_char_p, c_int, c_int] # /usr/include/X11/Xlib.h:3386 XStoreBytes = _lib.XStoreBytes XStoreBytes.restype = c_int XStoreBytes.argtypes = [POINTER(Display), c_char_p, c_int] # /usr/include/X11/Xlib.h:3392 XStoreColor = _lib.XStoreColor XStoreColor.restype = c_int XStoreColor.argtypes = [POINTER(Display), Colormap, POINTER(XColor)] # /usr/include/X11/Xlib.h:3398 XStoreColors = _lib.XStoreColors XStoreColors.restype = c_int XStoreColors.argtypes = [POINTER(Display), Colormap, POINTER(XColor), c_int] # /usr/include/X11/Xlib.h:3405 XStoreName = _lib.XStoreName XStoreName.restype = c_int XStoreName.argtypes = [POINTER(Display), Window, c_char_p] # /usr/include/X11/Xlib.h:3411 XStoreNamedColor = _lib.XStoreNamedColor XStoreNamedColor.restype = c_int XStoreNamedColor.argtypes = [POINTER(Display), Colormap, c_char_p, c_ulong, c_int] # /usr/include/X11/Xlib.h:3419 XSync = _lib.XSync XSync.restype = c_int XSync.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:3424 XTextExtents = _lib.XTextExtents XTextExtents.restype = c_int XTextExtents.argtypes = [POINTER(XFontStruct), c_char_p, c_int, POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(XCharStruct)] # /usr/include/X11/Xlib.h:3434 XTextExtents16 = _lib.XTextExtents16 XTextExtents16.restype = c_int XTextExtents16.argtypes = [POINTER(XFontStruct), POINTER(XChar2b), c_int, POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(XCharStruct)] # /usr/include/X11/Xlib.h:3444 XTextWidth = _lib.XTextWidth XTextWidth.restype = c_int XTextWidth.argtypes = [POINTER(XFontStruct), c_char_p, c_int] # /usr/include/X11/Xlib.h:3450 XTextWidth16 = _lib.XTextWidth16 XTextWidth16.restype = c_int XTextWidth16.argtypes = [POINTER(XFontStruct), POINTER(XChar2b), c_int] # /usr/include/X11/Xlib.h:3456 XTranslateCoordinates = _lib.XTranslateCoordinates XTranslateCoordinates.restype = c_int XTranslateCoordinates.argtypes = [POINTER(Display), Window, Window, c_int, c_int, POINTER(c_int), POINTER(c_int), POINTER(Window)] # /usr/include/X11/Xlib.h:3467 XUndefineCursor = _lib.XUndefineCursor XUndefineCursor.restype = c_int XUndefineCursor.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:3472 XUngrabButton = _lib.XUngrabButton XUngrabButton.restype = c_int XUngrabButton.argtypes = [POINTER(Display), c_uint, c_uint, Window] # /usr/include/X11/Xlib.h:3479 XUngrabKey = _lib.XUngrabKey XUngrabKey.restype = c_int XUngrabKey.argtypes = [POINTER(Display), c_int, c_uint, Window] # /usr/include/X11/Xlib.h:3486 XUngrabKeyboard = _lib.XUngrabKeyboard XUngrabKeyboard.restype = c_int XUngrabKeyboard.argtypes = [POINTER(Display), Time] # /usr/include/X11/Xlib.h:3491 XUngrabPointer = _lib.XUngrabPointer XUngrabPointer.restype = c_int XUngrabPointer.argtypes = [POINTER(Display), Time] # /usr/include/X11/Xlib.h:3496 XUngrabServer = _lib.XUngrabServer XUngrabServer.restype = c_int XUngrabServer.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:3500 XUninstallColormap = _lib.XUninstallColormap XUninstallColormap.restype = c_int XUninstallColormap.argtypes = [POINTER(Display), Colormap] # /usr/include/X11/Xlib.h:3505 XUnloadFont = _lib.XUnloadFont XUnloadFont.restype = c_int XUnloadFont.argtypes = [POINTER(Display), Font] # /usr/include/X11/Xlib.h:3510 XUnmapSubwindows = _lib.XUnmapSubwindows XUnmapSubwindows.restype = c_int XUnmapSubwindows.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:3515 XUnmapWindow = _lib.XUnmapWindow XUnmapWindow.restype = c_int XUnmapWindow.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:3520 XVendorRelease = _lib.XVendorRelease XVendorRelease.restype = c_int XVendorRelease.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:3524 XWarpPointer = _lib.XWarpPointer XWarpPointer.restype = c_int XWarpPointer.argtypes = [POINTER(Display), Window, Window, c_int, c_int, c_uint, c_uint, c_int, c_int] # /usr/include/X11/Xlib.h:3536 XWidthMMOfScreen = _lib.XWidthMMOfScreen XWidthMMOfScreen.restype = c_int XWidthMMOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:3540 XWidthOfScreen = _lib.XWidthOfScreen XWidthOfScreen.restype = c_int XWidthOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:3544 XWindowEvent = _lib.XWindowEvent XWindowEvent.restype = c_int XWindowEvent.argtypes = [POINTER(Display), Window, c_long, POINTER(XEvent)] # /usr/include/X11/Xlib.h:3551 XWriteBitmapFile = _lib.XWriteBitmapFile XWriteBitmapFile.restype = c_int XWriteBitmapFile.argtypes = [POINTER(Display), c_char_p, Pixmap, c_uint, c_uint, c_int, c_int] # /usr/include/X11/Xlib.h:3561 XSupportsLocale = _lib.XSupportsLocale XSupportsLocale.restype = c_int XSupportsLocale.argtypes = [] # /usr/include/X11/Xlib.h:3563 XSetLocaleModifiers = _lib.XSetLocaleModifiers XSetLocaleModifiers.restype = c_char_p XSetLocaleModifiers.argtypes = [c_char_p] class struct__XrmHashBucketRec(Structure): __slots__ = [ ] struct__XrmHashBucketRec._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/X11/Xlib.h:3567 XOpenOM = _lib.XOpenOM XOpenOM.restype = XOM XOpenOM.argtypes = [POINTER(Display), POINTER(struct__XrmHashBucketRec), c_char_p, c_char_p] # /usr/include/X11/Xlib.h:3574 XCloseOM = _lib.XCloseOM XCloseOM.restype = c_int XCloseOM.argtypes = [XOM] # /usr/include/X11/Xlib.h:3578 XSetOMValues = _lib.XSetOMValues XSetOMValues.restype = c_char_p XSetOMValues.argtypes = [XOM] # /usr/include/X11/Xlib.h:3583 XGetOMValues = _lib.XGetOMValues XGetOMValues.restype = c_char_p XGetOMValues.argtypes = [XOM] # /usr/include/X11/Xlib.h:3588 XDisplayOfOM = _lib.XDisplayOfOM XDisplayOfOM.restype = POINTER(Display) XDisplayOfOM.argtypes = [XOM] # /usr/include/X11/Xlib.h:3592 XLocaleOfOM = _lib.XLocaleOfOM XLocaleOfOM.restype = c_char_p XLocaleOfOM.argtypes = [XOM] # /usr/include/X11/Xlib.h:3596 XCreateOC = _lib.XCreateOC XCreateOC.restype = XOC XCreateOC.argtypes = [XOM] # /usr/include/X11/Xlib.h:3601 XDestroyOC = _lib.XDestroyOC XDestroyOC.restype = None XDestroyOC.argtypes = [XOC] # /usr/include/X11/Xlib.h:3605 XOMOfOC = _lib.XOMOfOC XOMOfOC.restype = XOM XOMOfOC.argtypes = [XOC] # /usr/include/X11/Xlib.h:3609 XSetOCValues = _lib.XSetOCValues XSetOCValues.restype = c_char_p XSetOCValues.argtypes = [XOC] # /usr/include/X11/Xlib.h:3614 XGetOCValues = _lib.XGetOCValues XGetOCValues.restype = c_char_p XGetOCValues.argtypes = [XOC] # /usr/include/X11/Xlib.h:3619 XCreateFontSet = _lib.XCreateFontSet XCreateFontSet.restype = XFontSet XCreateFontSet.argtypes = [POINTER(Display), c_char_p, POINTER(POINTER(c_char_p)), POINTER(c_int), POINTER(c_char_p)] # /usr/include/X11/Xlib.h:3627 XFreeFontSet = _lib.XFreeFontSet XFreeFontSet.restype = None XFreeFontSet.argtypes = [POINTER(Display), XFontSet] # /usr/include/X11/Xlib.h:3632 XFontsOfFontSet = _lib.XFontsOfFontSet XFontsOfFontSet.restype = c_int XFontsOfFontSet.argtypes = [XFontSet, POINTER(POINTER(POINTER(XFontStruct))), POINTER(POINTER(c_char_p))] # /usr/include/X11/Xlib.h:3638 XBaseFontNameListOfFontSet = _lib.XBaseFontNameListOfFontSet XBaseFontNameListOfFontSet.restype = c_char_p XBaseFontNameListOfFontSet.argtypes = [XFontSet] # /usr/include/X11/Xlib.h:3642 XLocaleOfFontSet = _lib.XLocaleOfFontSet XLocaleOfFontSet.restype = c_char_p XLocaleOfFontSet.argtypes = [XFontSet] # /usr/include/X11/Xlib.h:3646 XContextDependentDrawing = _lib.XContextDependentDrawing XContextDependentDrawing.restype = c_int XContextDependentDrawing.argtypes = [XFontSet] # /usr/include/X11/Xlib.h:3650 XDirectionalDependentDrawing = _lib.XDirectionalDependentDrawing XDirectionalDependentDrawing.restype = c_int XDirectionalDependentDrawing.argtypes = [XFontSet] # /usr/include/X11/Xlib.h:3654 XContextualDrawing = _lib.XContextualDrawing XContextualDrawing.restype = c_int XContextualDrawing.argtypes = [XFontSet] # /usr/include/X11/Xlib.h:3658 XExtentsOfFontSet = _lib.XExtentsOfFontSet XExtentsOfFontSet.restype = POINTER(XFontSetExtents) XExtentsOfFontSet.argtypes = [XFontSet] # /usr/include/X11/Xlib.h:3662 XmbTextEscapement = _lib.XmbTextEscapement XmbTextEscapement.restype = c_int XmbTextEscapement.argtypes = [XFontSet, c_char_p, c_int] # /usr/include/X11/Xlib.h:3668 XwcTextEscapement = _lib.XwcTextEscapement XwcTextEscapement.restype = c_int XwcTextEscapement.argtypes = [XFontSet, c_wchar_p, c_int] # /usr/include/X11/Xlib.h:3674 Xutf8TextEscapement = _lib.Xutf8TextEscapement Xutf8TextEscapement.restype = c_int Xutf8TextEscapement.argtypes = [XFontSet, c_char_p, c_int] # /usr/include/X11/Xlib.h:3680 XmbTextExtents = _lib.XmbTextExtents XmbTextExtents.restype = c_int XmbTextExtents.argtypes = [XFontSet, c_char_p, c_int, POINTER(XRectangle), POINTER(XRectangle)] # /usr/include/X11/Xlib.h:3688 XwcTextExtents = _lib.XwcTextExtents XwcTextExtents.restype = c_int XwcTextExtents.argtypes = [XFontSet, c_wchar_p, c_int, POINTER(XRectangle), POINTER(XRectangle)] # /usr/include/X11/Xlib.h:3696 Xutf8TextExtents = _lib.Xutf8TextExtents Xutf8TextExtents.restype = c_int Xutf8TextExtents.argtypes = [XFontSet, c_char_p, c_int, POINTER(XRectangle), POINTER(XRectangle)] # /usr/include/X11/Xlib.h:3704 XmbTextPerCharExtents = _lib.XmbTextPerCharExtents XmbTextPerCharExtents.restype = c_int XmbTextPerCharExtents.argtypes = [XFontSet, c_char_p, c_int, POINTER(XRectangle), POINTER(XRectangle), c_int, POINTER(c_int), POINTER(XRectangle), POINTER(XRectangle)] # /usr/include/X11/Xlib.h:3716 XwcTextPerCharExtents = _lib.XwcTextPerCharExtents XwcTextPerCharExtents.restype = c_int XwcTextPerCharExtents.argtypes = [XFontSet, c_wchar_p, c_int, POINTER(XRectangle), POINTER(XRectangle), c_int, POINTER(c_int), POINTER(XRectangle), POINTER(XRectangle)] # /usr/include/X11/Xlib.h:3728 Xutf8TextPerCharExtents = _lib.Xutf8TextPerCharExtents Xutf8TextPerCharExtents.restype = c_int Xutf8TextPerCharExtents.argtypes = [XFontSet, c_char_p, c_int, POINTER(XRectangle), POINTER(XRectangle), c_int, POINTER(c_int), POINTER(XRectangle), POINTER(XRectangle)] # /usr/include/X11/Xlib.h:3740 XmbDrawText = _lib.XmbDrawText XmbDrawText.restype = None XmbDrawText.argtypes = [POINTER(Display), Drawable, GC, c_int, c_int, POINTER(XmbTextItem), c_int] # /usr/include/X11/Xlib.h:3750 XwcDrawText = _lib.XwcDrawText XwcDrawText.restype = None XwcDrawText.argtypes = [POINTER(Display), Drawable, GC, c_int, c_int, POINTER(XwcTextItem), c_int] # /usr/include/X11/Xlib.h:3760 Xutf8DrawText = _lib.Xutf8DrawText Xutf8DrawText.restype = None Xutf8DrawText.argtypes = [POINTER(Display), Drawable, GC, c_int, c_int, POINTER(XmbTextItem), c_int] # /usr/include/X11/Xlib.h:3770 XmbDrawString = _lib.XmbDrawString XmbDrawString.restype = None XmbDrawString.argtypes = [POINTER(Display), Drawable, XFontSet, GC, c_int, c_int, c_char_p, c_int] # /usr/include/X11/Xlib.h:3781 XwcDrawString = _lib.XwcDrawString XwcDrawString.restype = None XwcDrawString.argtypes = [POINTER(Display), Drawable, XFontSet, GC, c_int, c_int, c_wchar_p, c_int] # /usr/include/X11/Xlib.h:3792 Xutf8DrawString = _lib.Xutf8DrawString Xutf8DrawString.restype = None Xutf8DrawString.argtypes = [POINTER(Display), Drawable, XFontSet, GC, c_int, c_int, c_char_p, c_int] # /usr/include/X11/Xlib.h:3803 XmbDrawImageString = _lib.XmbDrawImageString XmbDrawImageString.restype = None XmbDrawImageString.argtypes = [POINTER(Display), Drawable, XFontSet, GC, c_int, c_int, c_char_p, c_int] # /usr/include/X11/Xlib.h:3814 XwcDrawImageString = _lib.XwcDrawImageString XwcDrawImageString.restype = None XwcDrawImageString.argtypes = [POINTER(Display), Drawable, XFontSet, GC, c_int, c_int, c_wchar_p, c_int] # /usr/include/X11/Xlib.h:3825 Xutf8DrawImageString = _lib.Xutf8DrawImageString Xutf8DrawImageString.restype = None Xutf8DrawImageString.argtypes = [POINTER(Display), Drawable, XFontSet, GC, c_int, c_int, c_char_p, c_int] class struct__XrmHashBucketRec(Structure): __slots__ = [ ] struct__XrmHashBucketRec._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/X11/Xlib.h:3836 XOpenIM = _lib.XOpenIM XOpenIM.restype = XIM XOpenIM.argtypes = [POINTER(Display), POINTER(struct__XrmHashBucketRec), c_char_p, c_char_p] # /usr/include/X11/Xlib.h:3843 XCloseIM = _lib.XCloseIM XCloseIM.restype = c_int XCloseIM.argtypes = [XIM] # /usr/include/X11/Xlib.h:3847 XGetIMValues = _lib.XGetIMValues XGetIMValues.restype = c_char_p XGetIMValues.argtypes = [XIM] # /usr/include/X11/Xlib.h:3851 XSetIMValues = _lib.XSetIMValues XSetIMValues.restype = c_char_p XSetIMValues.argtypes = [XIM] # /usr/include/X11/Xlib.h:3855 XDisplayOfIM = _lib.XDisplayOfIM XDisplayOfIM.restype = POINTER(Display) XDisplayOfIM.argtypes = [XIM] # /usr/include/X11/Xlib.h:3859 XLocaleOfIM = _lib.XLocaleOfIM XLocaleOfIM.restype = c_char_p XLocaleOfIM.argtypes = [XIM] # /usr/include/X11/Xlib.h:3863 XCreateIC = _lib.XCreateIC XCreateIC.restype = XIC XCreateIC.argtypes = [XIM] # /usr/include/X11/Xlib.h:3867 XDestroyIC = _lib.XDestroyIC XDestroyIC.restype = None XDestroyIC.argtypes = [XIC] # /usr/include/X11/Xlib.h:3871 XSetICFocus = _lib.XSetICFocus XSetICFocus.restype = None XSetICFocus.argtypes = [XIC] # /usr/include/X11/Xlib.h:3875 XUnsetICFocus = _lib.XUnsetICFocus XUnsetICFocus.restype = None XUnsetICFocus.argtypes = [XIC] # /usr/include/X11/Xlib.h:3879 XwcResetIC = _lib.XwcResetIC XwcResetIC.restype = c_wchar_p XwcResetIC.argtypes = [XIC] # /usr/include/X11/Xlib.h:3883 XmbResetIC = _lib.XmbResetIC XmbResetIC.restype = c_char_p XmbResetIC.argtypes = [XIC] # /usr/include/X11/Xlib.h:3887 Xutf8ResetIC = _lib.Xutf8ResetIC Xutf8ResetIC.restype = c_char_p Xutf8ResetIC.argtypes = [XIC] # /usr/include/X11/Xlib.h:3891 XSetICValues = _lib.XSetICValues XSetICValues.restype = c_char_p XSetICValues.argtypes = [XIC] # /usr/include/X11/Xlib.h:3895 XGetICValues = _lib.XGetICValues XGetICValues.restype = c_char_p XGetICValues.argtypes = [XIC] # /usr/include/X11/Xlib.h:3899 XIMOfIC = _lib.XIMOfIC XIMOfIC.restype = XIM XIMOfIC.argtypes = [XIC] # /usr/include/X11/Xlib.h:3903 XFilterEvent = _lib.XFilterEvent XFilterEvent.restype = c_int XFilterEvent.argtypes = [POINTER(XEvent), Window] # /usr/include/X11/Xlib.h:3908 XmbLookupString = _lib.XmbLookupString XmbLookupString.restype = c_int XmbLookupString.argtypes = [XIC, POINTER(XKeyPressedEvent), c_char_p, c_int, POINTER(KeySym), POINTER(c_int)] # /usr/include/X11/Xlib.h:3917 XwcLookupString = _lib.XwcLookupString XwcLookupString.restype = c_int XwcLookupString.argtypes = [XIC, POINTER(XKeyPressedEvent), c_wchar_p, c_int, POINTER(KeySym), POINTER(c_int)] # /usr/include/X11/Xlib.h:3926 Xutf8LookupString = _lib.Xutf8LookupString Xutf8LookupString.restype = c_int Xutf8LookupString.argtypes = [XIC, POINTER(XKeyPressedEvent), c_char_p, c_int, POINTER(KeySym), POINTER(c_int)] # /usr/include/X11/Xlib.h:3935 XVaCreateNestedList = _lib.XVaCreateNestedList XVaCreateNestedList.restype = XVaNestedList XVaCreateNestedList.argtypes = [c_int] class struct__XrmHashBucketRec(Structure): __slots__ = [ ] struct__XrmHashBucketRec._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/X11/Xlib.h:3941 XRegisterIMInstantiateCallback = _lib.XRegisterIMInstantiateCallback XRegisterIMInstantiateCallback.restype = c_int XRegisterIMInstantiateCallback.argtypes = [POINTER(Display), POINTER(struct__XrmHashBucketRec), c_char_p, c_char_p, XIDProc, XPointer] class struct__XrmHashBucketRec(Structure): __slots__ = [ ] struct__XrmHashBucketRec._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/X11/Xlib.h:3950 XUnregisterIMInstantiateCallback = _lib.XUnregisterIMInstantiateCallback XUnregisterIMInstantiateCallback.restype = c_int XUnregisterIMInstantiateCallback.argtypes = [POINTER(Display), POINTER(struct__XrmHashBucketRec), c_char_p, c_char_p, XIDProc, XPointer] XConnectionWatchProc = CFUNCTYPE(None, POINTER(Display), XPointer, c_int, c_int, POINTER(XPointer)) # /usr/include/X11/Xlib.h:3959 # /usr/include/X11/Xlib.h:3968 XInternalConnectionNumbers = _lib.XInternalConnectionNumbers XInternalConnectionNumbers.restype = c_int XInternalConnectionNumbers.argtypes = [POINTER(Display), POINTER(POINTER(c_int)), POINTER(c_int)] # /usr/include/X11/Xlib.h:3974 XProcessInternalConnection = _lib.XProcessInternalConnection XProcessInternalConnection.restype = None XProcessInternalConnection.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:3979 XAddConnectionWatch = _lib.XAddConnectionWatch XAddConnectionWatch.restype = c_int XAddConnectionWatch.argtypes = [POINTER(Display), XConnectionWatchProc, XPointer] # /usr/include/X11/Xlib.h:3985 XRemoveConnectionWatch = _lib.XRemoveConnectionWatch XRemoveConnectionWatch.restype = None XRemoveConnectionWatch.argtypes = [POINTER(Display), XConnectionWatchProc, XPointer] # /usr/include/X11/Xlib.h:3991 XSetAuthorization = _lib.XSetAuthorization XSetAuthorization.restype = None XSetAuthorization.argtypes = [c_char_p, c_int, c_char_p, c_int] # /usr/include/X11/Xlib.h:3998 _Xmbtowc = _lib._Xmbtowc _Xmbtowc.restype = c_int _Xmbtowc.argtypes = [c_wchar_p, c_char_p, c_int] # /usr/include/X11/Xlib.h:4009 _Xwctomb = _lib._Xwctomb _Xwctomb.restype = c_int _Xwctomb.argtypes = [c_char_p, c_wchar] # /usr/include/X11/Xlib.h:4014 XGetEventData = _lib.XGetEventData XGetEventData.restype = c_int XGetEventData.argtypes = [POINTER(Display), POINTER(XGenericEventCookie)] # /usr/include/X11/Xlib.h:4019 XFreeEventData = _lib.XFreeEventData XFreeEventData.restype = None XFreeEventData.argtypes = [POINTER(Display), POINTER(XGenericEventCookie)] NoValue = 0 # /usr/include/X11/Xutil.h:4805 XValue = 1 # /usr/include/X11/Xutil.h:4806 YValue = 2 # /usr/include/X11/Xutil.h:4807 WidthValue = 4 # /usr/include/X11/Xutil.h:4808 HeightValue = 8 # /usr/include/X11/Xutil.h:4809 AllValues = 15 # /usr/include/X11/Xutil.h:4810 XNegative = 16 # /usr/include/X11/Xutil.h:4811 YNegative = 32 # /usr/include/X11/Xutil.h:4812 class struct_anon_95(Structure): __slots__ = [ 'flags', 'x', 'y', 'width', 'height', 'min_width', 'min_height', 'max_width', 'max_height', 'width_inc', 'height_inc', 'min_aspect', 'max_aspect', 'base_width', 'base_height', 'win_gravity', ] class struct_anon_96(Structure): __slots__ = [ 'x', 'y', ] struct_anon_96._fields_ = [ ('x', c_int), ('y', c_int), ] class struct_anon_97(Structure): __slots__ = [ 'x', 'y', ] struct_anon_97._fields_ = [ ('x', c_int), ('y', c_int), ] struct_anon_95._fields_ = [ ('flags', c_long), ('x', c_int), ('y', c_int), ('width', c_int), ('height', c_int), ('min_width', c_int), ('min_height', c_int), ('max_width', c_int), ('max_height', c_int), ('width_inc', c_int), ('height_inc', c_int), ('min_aspect', struct_anon_96), ('max_aspect', struct_anon_97), ('base_width', c_int), ('base_height', c_int), ('win_gravity', c_int), ] XSizeHints = struct_anon_95 # /usr/include/X11/Xutil.h:4831 USPosition = 1 # /usr/include/X11/Xutil.h:4839 USSize = 2 # /usr/include/X11/Xutil.h:4840 PPosition = 4 # /usr/include/X11/Xutil.h:4842 PSize = 8 # /usr/include/X11/Xutil.h:4843 PMinSize = 16 # /usr/include/X11/Xutil.h:4844 PMaxSize = 32 # /usr/include/X11/Xutil.h:4845 PResizeInc = 64 # /usr/include/X11/Xutil.h:4846 PAspect = 128 # /usr/include/X11/Xutil.h:4847 PBaseSize = 256 # /usr/include/X11/Xutil.h:4848 PWinGravity = 512 # /usr/include/X11/Xutil.h:4849 PAllHints = 252 # /usr/include/X11/Xutil.h:4852 class struct_anon_98(Structure): __slots__ = [ 'flags', 'input', 'initial_state', 'icon_pixmap', 'icon_window', 'icon_x', 'icon_y', 'icon_mask', 'window_group', ] struct_anon_98._fields_ = [ ('flags', c_long), ('input', c_int), ('initial_state', c_int), ('icon_pixmap', Pixmap), ('icon_window', Window), ('icon_x', c_int), ('icon_y', c_int), ('icon_mask', Pixmap), ('window_group', XID), ] XWMHints = struct_anon_98 # /usr/include/X11/Xutil.h:4867 InputHint = 1 # /usr/include/X11/Xutil.h:4871 StateHint = 2 # /usr/include/X11/Xutil.h:4872 IconPixmapHint = 4 # /usr/include/X11/Xutil.h:4873 IconWindowHint = 8 # /usr/include/X11/Xutil.h:4874 IconPositionHint = 16 # /usr/include/X11/Xutil.h:4875 IconMaskHint = 32 # /usr/include/X11/Xutil.h:4876 WindowGroupHint = 64 # /usr/include/X11/Xutil.h:4877 AllHints = 127 # /usr/include/X11/Xutil.h:4878 XUrgencyHint = 256 # /usr/include/X11/Xutil.h:4880 WithdrawnState = 0 # /usr/include/X11/Xutil.h:4883 NormalState = 1 # /usr/include/X11/Xutil.h:4884 IconicState = 3 # /usr/include/X11/Xutil.h:4885 DontCareState = 0 # /usr/include/X11/Xutil.h:4890 ZoomState = 2 # /usr/include/X11/Xutil.h:4891 InactiveState = 4 # /usr/include/X11/Xutil.h:4892 class struct_anon_99(Structure): __slots__ = [ 'value', 'encoding', 'format', 'nitems', ] struct_anon_99._fields_ = [ ('value', POINTER(c_ubyte)), ('encoding', Atom), ('format', c_int), ('nitems', c_ulong), ] XTextProperty = struct_anon_99 # /usr/include/X11/Xutil.h:4905 XNoMemory = -1 # /usr/include/X11/Xutil.h:4907 XLocaleNotSupported = -2 # /usr/include/X11/Xutil.h:4908 XConverterNotFound = -3 # /usr/include/X11/Xutil.h:4909 enum_anon_100 = c_int XStringStyle = 0 XCompoundTextStyle = 1 XTextStyle = 2 XStdICCTextStyle = 3 XUTF8StringStyle = 4 XICCEncodingStyle = enum_anon_100 # /usr/include/X11/Xutil.h:4918 class struct_anon_101(Structure): __slots__ = [ 'min_width', 'min_height', 'max_width', 'max_height', 'width_inc', 'height_inc', ] struct_anon_101._fields_ = [ ('min_width', c_int), ('min_height', c_int), ('max_width', c_int), ('max_height', c_int), ('width_inc', c_int), ('height_inc', c_int), ] XIconSize = struct_anon_101 # /usr/include/X11/Xutil.h:4924 class struct_anon_102(Structure): __slots__ = [ 'res_name', 'res_class', ] struct_anon_102._fields_ = [ ('res_name', c_char_p), ('res_class', c_char_p), ] XClassHint = struct_anon_102 # /usr/include/X11/Xutil.h:4929 class struct__XComposeStatus(Structure): __slots__ = [ 'compose_ptr', 'chars_matched', ] struct__XComposeStatus._fields_ = [ ('compose_ptr', XPointer), ('chars_matched', c_int), ] XComposeStatus = struct__XComposeStatus # /usr/include/X11/Xutil.h:4971 class struct__XRegion(Structure): __slots__ = [ ] struct__XRegion._fields_ = [ ('_opaque_struct', c_int) ] class struct__XRegion(Structure): __slots__ = [ ] struct__XRegion._fields_ = [ ('_opaque_struct', c_int) ] Region = POINTER(struct__XRegion) # /usr/include/X11/Xutil.h:5010 RectangleOut = 0 # /usr/include/X11/Xutil.h:5014 RectangleIn = 1 # /usr/include/X11/Xutil.h:5015 RectanglePart = 2 # /usr/include/X11/Xutil.h:5016 class struct_anon_103(Structure): __slots__ = [ 'visual', 'visualid', 'screen', 'depth', 'class', 'red_mask', 'green_mask', 'blue_mask', 'colormap_size', 'bits_per_rgb', ] struct_anon_103._fields_ = [ ('visual', POINTER(Visual)), ('visualid', VisualID), ('screen', c_int), ('depth', c_int), ('class', c_int), ('red_mask', c_ulong), ('green_mask', c_ulong), ('blue_mask', c_ulong), ('colormap_size', c_int), ('bits_per_rgb', c_int), ] XVisualInfo = struct_anon_103 # /usr/include/X11/Xutil.h:5039 VisualNoMask = 0 # /usr/include/X11/Xutil.h:5041 VisualIDMask = 1 # /usr/include/X11/Xutil.h:5042 VisualScreenMask = 2 # /usr/include/X11/Xutil.h:5043 VisualDepthMask = 4 # /usr/include/X11/Xutil.h:5044 VisualClassMask = 8 # /usr/include/X11/Xutil.h:5045 VisualRedMaskMask = 16 # /usr/include/X11/Xutil.h:5046 VisualGreenMaskMask = 32 # /usr/include/X11/Xutil.h:5047 VisualBlueMaskMask = 64 # /usr/include/X11/Xutil.h:5048 VisualColormapSizeMask = 128 # /usr/include/X11/Xutil.h:5049 VisualBitsPerRGBMask = 256 # /usr/include/X11/Xutil.h:5050 VisualAllMask = 511 # /usr/include/X11/Xutil.h:5051 class struct_anon_104(Structure): __slots__ = [ 'colormap', 'red_max', 'red_mult', 'green_max', 'green_mult', 'blue_max', 'blue_mult', 'base_pixel', 'visualid', 'killid', ] struct_anon_104._fields_ = [ ('colormap', Colormap), ('red_max', c_ulong), ('red_mult', c_ulong), ('green_max', c_ulong), ('green_mult', c_ulong), ('blue_max', c_ulong), ('blue_mult', c_ulong), ('base_pixel', c_ulong), ('visualid', VisualID), ('killid', XID), ] XStandardColormap = struct_anon_104 # /usr/include/X11/Xutil.h:5068 BitmapSuccess = 0 # /usr/include/X11/Xutil.h:5076 BitmapOpenFailed = 1 # /usr/include/X11/Xutil.h:5077 BitmapFileInvalid = 2 # /usr/include/X11/Xutil.h:5078 BitmapNoMemory = 3 # /usr/include/X11/Xutil.h:5079 XCSUCCESS = 0 # /usr/include/X11/Xutil.h:5090 XCNOMEM = 1 # /usr/include/X11/Xutil.h:5091 XCNOENT = 2 # /usr/include/X11/Xutil.h:5092 XContext = c_int # /usr/include/X11/Xutil.h:5094 # /usr/include/X11/Xutil.h:5103 XAllocClassHint = _lib.XAllocClassHint XAllocClassHint.restype = POINTER(XClassHint) XAllocClassHint.argtypes = [] # /usr/include/X11/Xutil.h:5107 XAllocIconSize = _lib.XAllocIconSize XAllocIconSize.restype = POINTER(XIconSize) XAllocIconSize.argtypes = [] # /usr/include/X11/Xutil.h:5111 XAllocSizeHints = _lib.XAllocSizeHints XAllocSizeHints.restype = POINTER(XSizeHints) XAllocSizeHints.argtypes = [] # /usr/include/X11/Xutil.h:5115 XAllocStandardColormap = _lib.XAllocStandardColormap XAllocStandardColormap.restype = POINTER(XStandardColormap) XAllocStandardColormap.argtypes = [] # /usr/include/X11/Xutil.h:5119 XAllocWMHints = _lib.XAllocWMHints XAllocWMHints.restype = POINTER(XWMHints) XAllocWMHints.argtypes = [] # /usr/include/X11/Xutil.h:5123 XClipBox = _lib.XClipBox XClipBox.restype = c_int XClipBox.argtypes = [Region, POINTER(XRectangle)] # /usr/include/X11/Xutil.h:5128 XCreateRegion = _lib.XCreateRegion XCreateRegion.restype = Region XCreateRegion.argtypes = [] # /usr/include/X11/Xutil.h:5132 XDefaultString = _lib.XDefaultString XDefaultString.restype = c_char_p XDefaultString.argtypes = [] # /usr/include/X11/Xutil.h:5134 XDeleteContext = _lib.XDeleteContext XDeleteContext.restype = c_int XDeleteContext.argtypes = [POINTER(Display), XID, XContext] # /usr/include/X11/Xutil.h:5140 XDestroyRegion = _lib.XDestroyRegion XDestroyRegion.restype = c_int XDestroyRegion.argtypes = [Region] # /usr/include/X11/Xutil.h:5144 XEmptyRegion = _lib.XEmptyRegion XEmptyRegion.restype = c_int XEmptyRegion.argtypes = [Region] # /usr/include/X11/Xutil.h:5148 XEqualRegion = _lib.XEqualRegion XEqualRegion.restype = c_int XEqualRegion.argtypes = [Region, Region] # /usr/include/X11/Xutil.h:5153 XFindContext = _lib.XFindContext XFindContext.restype = c_int XFindContext.argtypes = [POINTER(Display), XID, XContext, POINTER(XPointer)] # /usr/include/X11/Xutil.h:5160 XGetClassHint = _lib.XGetClassHint XGetClassHint.restype = c_int XGetClassHint.argtypes = [POINTER(Display), Window, POINTER(XClassHint)] # /usr/include/X11/Xutil.h:5166 XGetIconSizes = _lib.XGetIconSizes XGetIconSizes.restype = c_int XGetIconSizes.argtypes = [POINTER(Display), Window, POINTER(POINTER(XIconSize)), POINTER(c_int)] # /usr/include/X11/Xutil.h:5173 XGetNormalHints = _lib.XGetNormalHints XGetNormalHints.restype = c_int XGetNormalHints.argtypes = [POINTER(Display), Window, POINTER(XSizeHints)] # /usr/include/X11/Xutil.h:5179 XGetRGBColormaps = _lib.XGetRGBColormaps XGetRGBColormaps.restype = c_int XGetRGBColormaps.argtypes = [POINTER(Display), Window, POINTER(POINTER(XStandardColormap)), POINTER(c_int), Atom] # /usr/include/X11/Xutil.h:5187 XGetSizeHints = _lib.XGetSizeHints XGetSizeHints.restype = c_int XGetSizeHints.argtypes = [POINTER(Display), Window, POINTER(XSizeHints), Atom] # /usr/include/X11/Xutil.h:5194 XGetStandardColormap = _lib.XGetStandardColormap XGetStandardColormap.restype = c_int XGetStandardColormap.argtypes = [POINTER(Display), Window, POINTER(XStandardColormap), Atom] # /usr/include/X11/Xutil.h:5201 XGetTextProperty = _lib.XGetTextProperty XGetTextProperty.restype = c_int XGetTextProperty.argtypes = [POINTER(Display), Window, POINTER(XTextProperty), Atom] # /usr/include/X11/Xutil.h:5208 XGetVisualInfo = _lib.XGetVisualInfo XGetVisualInfo.restype = POINTER(XVisualInfo) XGetVisualInfo.argtypes = [POINTER(Display), c_long, POINTER(XVisualInfo), POINTER(c_int)] # /usr/include/X11/Xutil.h:5215 XGetWMClientMachine = _lib.XGetWMClientMachine XGetWMClientMachine.restype = c_int XGetWMClientMachine.argtypes = [POINTER(Display), Window, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5221 XGetWMHints = _lib.XGetWMHints XGetWMHints.restype = POINTER(XWMHints) XGetWMHints.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xutil.h:5226 XGetWMIconName = _lib.XGetWMIconName XGetWMIconName.restype = c_int XGetWMIconName.argtypes = [POINTER(Display), Window, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5232 XGetWMName = _lib.XGetWMName XGetWMName.restype = c_int XGetWMName.argtypes = [POINTER(Display), Window, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5238 XGetWMNormalHints = _lib.XGetWMNormalHints XGetWMNormalHints.restype = c_int XGetWMNormalHints.argtypes = [POINTER(Display), Window, POINTER(XSizeHints), POINTER(c_long)] # /usr/include/X11/Xutil.h:5245 XGetWMSizeHints = _lib.XGetWMSizeHints XGetWMSizeHints.restype = c_int XGetWMSizeHints.argtypes = [POINTER(Display), Window, POINTER(XSizeHints), POINTER(c_long), Atom] # /usr/include/X11/Xutil.h:5253 XGetZoomHints = _lib.XGetZoomHints XGetZoomHints.restype = c_int XGetZoomHints.argtypes = [POINTER(Display), Window, POINTER(XSizeHints)] # /usr/include/X11/Xutil.h:5259 XIntersectRegion = _lib.XIntersectRegion XIntersectRegion.restype = c_int XIntersectRegion.argtypes = [Region, Region, Region] # /usr/include/X11/Xutil.h:5265 XConvertCase = _lib.XConvertCase XConvertCase.restype = None XConvertCase.argtypes = [KeySym, POINTER(KeySym), POINTER(KeySym)] # /usr/include/X11/Xutil.h:5271 XLookupString = _lib.XLookupString XLookupString.restype = c_int XLookupString.argtypes = [POINTER(XKeyEvent), c_char_p, c_int, POINTER(KeySym), POINTER(XComposeStatus)] # /usr/include/X11/Xutil.h:5279 XMatchVisualInfo = _lib.XMatchVisualInfo XMatchVisualInfo.restype = c_int XMatchVisualInfo.argtypes = [POINTER(Display), c_int, c_int, c_int, POINTER(XVisualInfo)] # /usr/include/X11/Xutil.h:5287 XOffsetRegion = _lib.XOffsetRegion XOffsetRegion.restype = c_int XOffsetRegion.argtypes = [Region, c_int, c_int] # /usr/include/X11/Xutil.h:5293 XPointInRegion = _lib.XPointInRegion XPointInRegion.restype = c_int XPointInRegion.argtypes = [Region, c_int, c_int] # /usr/include/X11/Xutil.h:5299 XPolygonRegion = _lib.XPolygonRegion XPolygonRegion.restype = Region XPolygonRegion.argtypes = [POINTER(XPoint), c_int, c_int] # /usr/include/X11/Xutil.h:5305 XRectInRegion = _lib.XRectInRegion XRectInRegion.restype = c_int XRectInRegion.argtypes = [Region, c_int, c_int, c_uint, c_uint] # /usr/include/X11/Xutil.h:5313 XSaveContext = _lib.XSaveContext XSaveContext.restype = c_int XSaveContext.argtypes = [POINTER(Display), XID, XContext, c_char_p] # /usr/include/X11/Xutil.h:5320 XSetClassHint = _lib.XSetClassHint XSetClassHint.restype = c_int XSetClassHint.argtypes = [POINTER(Display), Window, POINTER(XClassHint)] # /usr/include/X11/Xutil.h:5326 XSetIconSizes = _lib.XSetIconSizes XSetIconSizes.restype = c_int XSetIconSizes.argtypes = [POINTER(Display), Window, POINTER(XIconSize), c_int] # /usr/include/X11/Xutil.h:5333 XSetNormalHints = _lib.XSetNormalHints XSetNormalHints.restype = c_int XSetNormalHints.argtypes = [POINTER(Display), Window, POINTER(XSizeHints)] # /usr/include/X11/Xutil.h:5339 XSetRGBColormaps = _lib.XSetRGBColormaps XSetRGBColormaps.restype = None XSetRGBColormaps.argtypes = [POINTER(Display), Window, POINTER(XStandardColormap), c_int, Atom] # /usr/include/X11/Xutil.h:5347 XSetSizeHints = _lib.XSetSizeHints XSetSizeHints.restype = c_int XSetSizeHints.argtypes = [POINTER(Display), Window, POINTER(XSizeHints), Atom] # /usr/include/X11/Xutil.h:5354 XSetStandardProperties = _lib.XSetStandardProperties XSetStandardProperties.restype = c_int XSetStandardProperties.argtypes = [POINTER(Display), Window, c_char_p, c_char_p, Pixmap, POINTER(c_char_p), c_int, POINTER(XSizeHints)] # /usr/include/X11/Xutil.h:5365 XSetTextProperty = _lib.XSetTextProperty XSetTextProperty.restype = None XSetTextProperty.argtypes = [POINTER(Display), Window, POINTER(XTextProperty), Atom] # /usr/include/X11/Xutil.h:5372 XSetWMClientMachine = _lib.XSetWMClientMachine XSetWMClientMachine.restype = None XSetWMClientMachine.argtypes = [POINTER(Display), Window, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5378 XSetWMHints = _lib.XSetWMHints XSetWMHints.restype = c_int XSetWMHints.argtypes = [POINTER(Display), Window, POINTER(XWMHints)] # /usr/include/X11/Xutil.h:5384 XSetWMIconName = _lib.XSetWMIconName XSetWMIconName.restype = None XSetWMIconName.argtypes = [POINTER(Display), Window, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5390 XSetWMName = _lib.XSetWMName XSetWMName.restype = None XSetWMName.argtypes = [POINTER(Display), Window, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5396 XSetWMNormalHints = _lib.XSetWMNormalHints XSetWMNormalHints.restype = None XSetWMNormalHints.argtypes = [POINTER(Display), Window, POINTER(XSizeHints)] # /usr/include/X11/Xutil.h:5402 XSetWMProperties = _lib.XSetWMProperties XSetWMProperties.restype = None XSetWMProperties.argtypes = [POINTER(Display), Window, POINTER(XTextProperty), POINTER(XTextProperty), POINTER(c_char_p), c_int, POINTER(XSizeHints), POINTER(XWMHints), POINTER(XClassHint)] # /usr/include/X11/Xutil.h:5414 XmbSetWMProperties = _lib.XmbSetWMProperties XmbSetWMProperties.restype = None XmbSetWMProperties.argtypes = [POINTER(Display), Window, c_char_p, c_char_p, POINTER(c_char_p), c_int, POINTER(XSizeHints), POINTER(XWMHints), POINTER(XClassHint)] # /usr/include/X11/Xutil.h:5426 Xutf8SetWMProperties = _lib.Xutf8SetWMProperties Xutf8SetWMProperties.restype = None Xutf8SetWMProperties.argtypes = [POINTER(Display), Window, c_char_p, c_char_p, POINTER(c_char_p), c_int, POINTER(XSizeHints), POINTER(XWMHints), POINTER(XClassHint)] # /usr/include/X11/Xutil.h:5438 XSetWMSizeHints = _lib.XSetWMSizeHints XSetWMSizeHints.restype = None XSetWMSizeHints.argtypes = [POINTER(Display), Window, POINTER(XSizeHints), Atom] # /usr/include/X11/Xutil.h:5445 XSetRegion = _lib.XSetRegion XSetRegion.restype = c_int XSetRegion.argtypes = [POINTER(Display), GC, Region] # /usr/include/X11/Xutil.h:5451 XSetStandardColormap = _lib.XSetStandardColormap XSetStandardColormap.restype = None XSetStandardColormap.argtypes = [POINTER(Display), Window, POINTER(XStandardColormap), Atom] # /usr/include/X11/Xutil.h:5458 XSetZoomHints = _lib.XSetZoomHints XSetZoomHints.restype = c_int XSetZoomHints.argtypes = [POINTER(Display), Window, POINTER(XSizeHints)] # /usr/include/X11/Xutil.h:5464 XShrinkRegion = _lib.XShrinkRegion XShrinkRegion.restype = c_int XShrinkRegion.argtypes = [Region, c_int, c_int] # /usr/include/X11/Xutil.h:5470 XStringListToTextProperty = _lib.XStringListToTextProperty XStringListToTextProperty.restype = c_int XStringListToTextProperty.argtypes = [POINTER(c_char_p), c_int, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5476 XSubtractRegion = _lib.XSubtractRegion XSubtractRegion.restype = c_int XSubtractRegion.argtypes = [Region, Region, Region] # /usr/include/X11/Xutil.h:5482 XmbTextListToTextProperty = _lib.XmbTextListToTextProperty XmbTextListToTextProperty.restype = c_int XmbTextListToTextProperty.argtypes = [POINTER(Display), POINTER(c_char_p), c_int, XICCEncodingStyle, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5490 XwcTextListToTextProperty = _lib.XwcTextListToTextProperty XwcTextListToTextProperty.restype = c_int XwcTextListToTextProperty.argtypes = [POINTER(Display), POINTER(c_wchar_p), c_int, XICCEncodingStyle, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5498 Xutf8TextListToTextProperty = _lib.Xutf8TextListToTextProperty Xutf8TextListToTextProperty.restype = c_int Xutf8TextListToTextProperty.argtypes = [POINTER(Display), POINTER(c_char_p), c_int, XICCEncodingStyle, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5506 XwcFreeStringList = _lib.XwcFreeStringList XwcFreeStringList.restype = None XwcFreeStringList.argtypes = [POINTER(c_wchar_p)] # /usr/include/X11/Xutil.h:5510 XTextPropertyToStringList = _lib.XTextPropertyToStringList XTextPropertyToStringList.restype = c_int XTextPropertyToStringList.argtypes = [POINTER(XTextProperty), POINTER(POINTER(c_char_p)), POINTER(c_int)] # /usr/include/X11/Xutil.h:5516 XmbTextPropertyToTextList = _lib.XmbTextPropertyToTextList XmbTextPropertyToTextList.restype = c_int XmbTextPropertyToTextList.argtypes = [POINTER(Display), POINTER(XTextProperty), POINTER(POINTER(c_char_p)), POINTER(c_int)] # /usr/include/X11/Xutil.h:5523 XwcTextPropertyToTextList = _lib.XwcTextPropertyToTextList XwcTextPropertyToTextList.restype = c_int XwcTextPropertyToTextList.argtypes = [POINTER(Display), POINTER(XTextProperty), POINTER(POINTER(c_wchar_p)), POINTER(c_int)] # /usr/include/X11/Xutil.h:5530 Xutf8TextPropertyToTextList = _lib.Xutf8TextPropertyToTextList Xutf8TextPropertyToTextList.restype = c_int Xutf8TextPropertyToTextList.argtypes = [POINTER(Display), POINTER(XTextProperty), POINTER(POINTER(c_char_p)), POINTER(c_int)] # /usr/include/X11/Xutil.h:5537 XUnionRectWithRegion = _lib.XUnionRectWithRegion XUnionRectWithRegion.restype = c_int XUnionRectWithRegion.argtypes = [POINTER(XRectangle), Region, Region] # /usr/include/X11/Xutil.h:5543 XUnionRegion = _lib.XUnionRegion XUnionRegion.restype = c_int XUnionRegion.argtypes = [Region, Region, Region] # /usr/include/X11/Xutil.h:5549 XWMGeometry = _lib.XWMGeometry XWMGeometry.restype = c_int XWMGeometry.argtypes = [POINTER(Display), c_int, c_char_p, c_char_p, c_uint, POINTER(XSizeHints), POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xutil.h:5563 XXorRegion = _lib.XXorRegion XXorRegion.restype = c_int XXorRegion.argtypes = [Region, Region, Region] __all__ = ['XlibSpecificationRelease', 'X_PROTOCOL', 'X_PROTOCOL_REVISION', 'XID', 'Mask', 'Atom', 'VisualID', 'Time', 'Window', 'Drawable', 'Font', 'Pixmap', 'Cursor', 'Colormap', 'GContext', 'KeySym', 'KeyCode', 'None_', 'ParentRelative', 'CopyFromParent', 'PointerWindow', 'InputFocus', 'PointerRoot', 'AnyPropertyType', 'AnyKey', 'AnyButton', 'AllTemporary', 'CurrentTime', 'NoSymbol', 'NoEventMask', 'KeyPressMask', 'KeyReleaseMask', 'ButtonPressMask', 'ButtonReleaseMask', 'EnterWindowMask', 'LeaveWindowMask', 'PointerMotionMask', 'PointerMotionHintMask', 'Button1MotionMask', 'Button2MotionMask', 'Button3MotionMask', 'Button4MotionMask', 'Button5MotionMask', 'ButtonMotionMask', 'KeymapStateMask', 'ExposureMask', 'VisibilityChangeMask', 'StructureNotifyMask', 'ResizeRedirectMask', 'SubstructureNotifyMask', 'SubstructureRedirectMask', 'FocusChangeMask', 'PropertyChangeMask', 'ColormapChangeMask', 'OwnerGrabButtonMask', 'KeyPress', 'KeyRelease', 'ButtonPress', 'ButtonRelease', 'MotionNotify', 'EnterNotify', 'LeaveNotify', 'FocusIn', 'FocusOut', 'KeymapNotify', 'Expose', 'GraphicsExpose', 'NoExpose', 'VisibilityNotify', 'CreateNotify', 'DestroyNotify', 'UnmapNotify', 'MapNotify', 'MapRequest', 'ReparentNotify', 'ConfigureNotify', 'ConfigureRequest', 'GravityNotify', 'ResizeRequest', 'CirculateNotify', 'CirculateRequest', 'PropertyNotify', 'SelectionClear', 'SelectionRequest', 'SelectionNotify', 'ColormapNotify', 'ClientMessage', 'MappingNotify', 'GenericEvent', 'LASTEvent', 'ShiftMask', 'LockMask', 'ControlMask', 'Mod1Mask', 'Mod2Mask', 'Mod3Mask', 'Mod4Mask', 'Mod5Mask', 'ShiftMapIndex', 'LockMapIndex', 'ControlMapIndex', 'Mod1MapIndex', 'Mod2MapIndex', 'Mod3MapIndex', 'Mod4MapIndex', 'Mod5MapIndex', 'Button1Mask', 'Button2Mask', 'Button3Mask', 'Button4Mask', 'Button5Mask', 'AnyModifier', 'Button1', 'Button2', 'Button3', 'Button4', 'Button5', 'NotifyNormal', 'NotifyGrab', 'NotifyUngrab', 'NotifyWhileGrabbed', 'NotifyHint', 'NotifyAncestor', 'NotifyVirtual', 'NotifyInferior', 'NotifyNonlinear', 'NotifyNonlinearVirtual', 'NotifyPointer', 'NotifyPointerRoot', 'NotifyDetailNone', 'VisibilityUnobscured', 'VisibilityPartiallyObscured', 'VisibilityFullyObscured', 'PlaceOnTop', 'PlaceOnBottom', 'FamilyInternet', 'FamilyDECnet', 'FamilyChaos', 'FamilyInternet6', 'FamilyServerInterpreted', 'PropertyNewValue', 'PropertyDelete', 'ColormapUninstalled', 'ColormapInstalled', 'GrabModeSync', 'GrabModeAsync', 'GrabSuccess', 'AlreadyGrabbed', 'GrabInvalidTime', 'GrabNotViewable', 'GrabFrozen', 'AsyncPointer', 'SyncPointer', 'ReplayPointer', 'AsyncKeyboard', 'SyncKeyboard', 'ReplayKeyboard', 'AsyncBoth', 'SyncBoth', 'RevertToParent', 'Success', 'BadRequest', 'BadValue', 'BadWindow', 'BadPixmap', 'BadAtom', 'BadCursor', 'BadFont', 'BadMatch', 'BadDrawable', 'BadAccess', 'BadAlloc', 'BadColor', 'BadGC', 'BadIDChoice', 'BadName', 'BadLength', 'BadImplementation', 'FirstExtensionError', 'LastExtensionError', 'InputOutput', 'InputOnly', 'CWBackPixmap', 'CWBackPixel', 'CWBorderPixmap', 'CWBorderPixel', 'CWBitGravity', 'CWWinGravity', 'CWBackingStore', 'CWBackingPlanes', 'CWBackingPixel', 'CWOverrideRedirect', 'CWSaveUnder', 'CWEventMask', 'CWDontPropagate', 'CWColormap', 'CWCursor', 'CWX', 'CWY', 'CWWidth', 'CWHeight', 'CWBorderWidth', 'CWSibling', 'CWStackMode', 'ForgetGravity', 'NorthWestGravity', 'NorthGravity', 'NorthEastGravity', 'WestGravity', 'CenterGravity', 'EastGravity', 'SouthWestGravity', 'SouthGravity', 'SouthEastGravity', 'StaticGravity', 'UnmapGravity', 'NotUseful', 'WhenMapped', 'Always', 'IsUnmapped', 'IsUnviewable', 'IsViewable', 'SetModeInsert', 'SetModeDelete', 'DestroyAll', 'RetainPermanent', 'RetainTemporary', 'Above', 'Below', 'TopIf', 'BottomIf', 'Opposite', 'RaiseLowest', 'LowerHighest', 'PropModeReplace', 'PropModePrepend', 'PropModeAppend', 'GXclear', 'GXand', 'GXandReverse', 'GXcopy', 'GXandInverted', 'GXnoop', 'GXxor', 'GXor', 'GXnor', 'GXequiv', 'GXinvert', 'GXorReverse', 'GXcopyInverted', 'GXorInverted', 'GXnand', 'GXset', 'LineSolid', 'LineOnOffDash', 'LineDoubleDash', 'CapNotLast', 'CapButt', 'CapRound', 'CapProjecting', 'JoinMiter', 'JoinRound', 'JoinBevel', 'FillSolid', 'FillTiled', 'FillStippled', 'FillOpaqueStippled', 'EvenOddRule', 'WindingRule', 'ClipByChildren', 'IncludeInferiors', 'Unsorted', 'YSorted', 'YXSorted', 'YXBanded', 'CoordModeOrigin', 'CoordModePrevious', 'Complex', 'Nonconvex', 'Convex', 'ArcChord', 'ArcPieSlice', 'GCFunction', 'GCPlaneMask', 'GCForeground', 'GCBackground', 'GCLineWidth', 'GCLineStyle', 'GCCapStyle', 'GCJoinStyle', 'GCFillStyle', 'GCFillRule', 'GCTile', 'GCStipple', 'GCTileStipXOrigin', 'GCTileStipYOrigin', 'GCFont', 'GCSubwindowMode', 'GCGraphicsExposures', 'GCClipXOrigin', 'GCClipYOrigin', 'GCClipMask', 'GCDashOffset', 'GCDashList', 'GCArcMode', 'GCLastBit', 'FontLeftToRight', 'FontRightToLeft', 'FontChange', 'XYBitmap', 'XYPixmap', 'ZPixmap', 'AllocNone', 'AllocAll', 'DoRed', 'DoGreen', 'DoBlue', 'CursorShape', 'TileShape', 'StippleShape', 'AutoRepeatModeOff', 'AutoRepeatModeOn', 'AutoRepeatModeDefault', 'LedModeOff', 'LedModeOn', 'KBKeyClickPercent', 'KBBellPercent', 'KBBellPitch', 'KBBellDuration', 'KBLed', 'KBLedMode', 'KBKey', 'KBAutoRepeatMode', 'MappingSuccess', 'MappingBusy', 'MappingFailed', 'MappingModifier', 'MappingKeyboard', 'MappingPointer', 'DontPreferBlanking', 'PreferBlanking', 'DefaultBlanking', 'DisableScreenSaver', 'DisableScreenInterval', 'DontAllowExposures', 'AllowExposures', 'DefaultExposures', 'ScreenSaverReset', 'ScreenSaverActive', 'HostInsert', 'HostDelete', 'EnableAccess', 'DisableAccess', 'StaticGray', 'GrayScale', 'StaticColor', 'PseudoColor', 'TrueColor', 'DirectColor', 'LSBFirst', 'MSBFirst', '_Xmblen', 'X_HAVE_UTF8_STRING', 'XPointer', 'Bool', 'Status', 'True_', 'False_', 'QueuedAlready', 'QueuedAfterReading', 'QueuedAfterFlush', 'XExtData', 'XExtCodes', 'XPixmapFormatValues', 'XGCValues', 'GC', 'Visual', 'Depth', 'Screen', 'ScreenFormat', 'XSetWindowAttributes', 'XWindowAttributes', 'XHostAddress', 'XServerInterpretedAddress', 'XImage', 'XWindowChanges', 'XColor', 'XSegment', 'XPoint', 'XRectangle', 'XArc', 'XKeyboardControl', 'XKeyboardState', 'XTimeCoord', 'XModifierKeymap', 'Display', '_XPrivDisplay', 'XKeyEvent', 'XKeyPressedEvent', 'XKeyReleasedEvent', 'XButtonEvent', 'XButtonPressedEvent', 'XButtonReleasedEvent', 'XMotionEvent', 'XPointerMovedEvent', 'XCrossingEvent', 'XEnterWindowEvent', 'XLeaveWindowEvent', 'XFocusChangeEvent', 'XFocusInEvent', 'XFocusOutEvent', 'XKeymapEvent', 'XExposeEvent', 'XGraphicsExposeEvent', 'XNoExposeEvent', 'XVisibilityEvent', 'XCreateWindowEvent', 'XDestroyWindowEvent', 'XUnmapEvent', 'XMapEvent', 'XMapRequestEvent', 'XReparentEvent', 'XConfigureEvent', 'XGravityEvent', 'XResizeRequestEvent', 'XConfigureRequestEvent', 'XCirculateEvent', 'XCirculateRequestEvent', 'XPropertyEvent', 'XSelectionClearEvent', 'XSelectionRequestEvent', 'XSelectionEvent', 'XColormapEvent', 'XClientMessageEvent', 'XMappingEvent', 'XErrorEvent', 'XAnyEvent', 'XGenericEvent', 'XGenericEventCookie', 'XEvent', 'XCharStruct', 'XFontProp', 'XFontStruct', 'XTextItem', 'XChar2b', 'XTextItem16', 'XEDataObject', 'XFontSetExtents', 'XOM', 'XOC', 'XFontSet', 'XmbTextItem', 'XwcTextItem', 'XOMCharSetList', 'XOrientation', 'XOMOrientation_LTR_TTB', 'XOMOrientation_RTL_TTB', 'XOMOrientation_TTB_LTR', 'XOMOrientation_TTB_RTL', 'XOMOrientation_Context', 'XOMOrientation', 'XOMFontInfo', 'XIM', 'XIC', 'XIMProc', 'XICProc', 'XIDProc', 'XIMStyle', 'XIMStyles', 'XIMPreeditArea', 'XIMPreeditCallbacks', 'XIMPreeditPosition', 'XIMPreeditNothing', 'XIMPreeditNone', 'XIMStatusArea', 'XIMStatusCallbacks', 'XIMStatusNothing', 'XIMStatusNone', 'XBufferOverflow', 'XLookupNone', 'XLookupChars', 'XLookupKeySym', 'XLookupBoth', 'XVaNestedList', 'XIMCallback', 'XICCallback', 'XIMFeedback', 'XIMReverse', 'XIMUnderline', 'XIMHighlight', 'XIMPrimary', 'XIMSecondary', 'XIMTertiary', 'XIMVisibleToForward', 'XIMVisibleToBackword', 'XIMVisibleToCenter', 'XIMText', 'XIMPreeditState', 'XIMPreeditUnKnown', 'XIMPreeditEnable', 'XIMPreeditDisable', 'XIMPreeditStateNotifyCallbackStruct', 'XIMResetState', 'XIMInitialState', 'XIMPreserveState', 'XIMStringConversionFeedback', 'XIMStringConversionLeftEdge', 'XIMStringConversionRightEdge', 'XIMStringConversionTopEdge', 'XIMStringConversionBottomEdge', 'XIMStringConversionConcealed', 'XIMStringConversionWrapped', 'XIMStringConversionText', 'XIMStringConversionPosition', 'XIMStringConversionType', 'XIMStringConversionBuffer', 'XIMStringConversionLine', 'XIMStringConversionWord', 'XIMStringConversionChar', 'XIMStringConversionOperation', 'XIMStringConversionSubstitution', 'XIMStringConversionRetrieval', 'XIMCaretDirection', 'XIMForwardChar', 'XIMBackwardChar', 'XIMForwardWord', 'XIMBackwardWord', 'XIMCaretUp', 'XIMCaretDown', 'XIMNextLine', 'XIMPreviousLine', 'XIMLineStart', 'XIMLineEnd', 'XIMAbsolutePosition', 'XIMDontChange', 'XIMStringConversionCallbackStruct', 'XIMPreeditDrawCallbackStruct', 'XIMCaretStyle', 'XIMIsInvisible', 'XIMIsPrimary', 'XIMIsSecondary', 'XIMPreeditCaretCallbackStruct', 'XIMStatusDataType', 'XIMTextType', 'XIMBitmapType', 'XIMStatusDrawCallbackStruct', 'XIMHotKeyTrigger', 'XIMHotKeyTriggers', 'XIMHotKeyState', 'XIMHotKeyStateON', 'XIMHotKeyStateOFF', 'XIMValuesList', 'XLoadQueryFont', 'XQueryFont', 'XGetMotionEvents', 'XDeleteModifiermapEntry', 'XGetModifierMapping', 'XInsertModifiermapEntry', 'XNewModifiermap', 'XCreateImage', 'XInitImage', 'XGetImage', 'XGetSubImage', 'XOpenDisplay', 'XrmInitialize', 'XFetchBytes', 'XFetchBuffer', 'XGetAtomName', 'XGetAtomNames', 'XGetDefault', 'XDisplayName', 'XKeysymToString', 'XSynchronize', 'XSetAfterFunction', 'XInternAtom', 'XInternAtoms', 'XCopyColormapAndFree', 'XCreateColormap', 'XCreatePixmapCursor', 'XCreateGlyphCursor', 'XCreateFontCursor', 'XLoadFont', 'XCreateGC', 'XGContextFromGC', 'XFlushGC', 'XCreatePixmap', 'XCreateBitmapFromData', 'XCreatePixmapFromBitmapData', 'XCreateSimpleWindow', 'XGetSelectionOwner', 'XCreateWindow', 'XListInstalledColormaps', 'XListFonts', 'XListFontsWithInfo', 'XGetFontPath', 'XListExtensions', 'XListProperties', 'XListHosts', 'XKeycodeToKeysym', 'XLookupKeysym', 'XGetKeyboardMapping', 'XStringToKeysym', 'XMaxRequestSize', 'XExtendedMaxRequestSize', 'XResourceManagerString', 'XScreenResourceString', 'XDisplayMotionBufferSize', 'XVisualIDFromVisual', 'XInitThreads', 'XLockDisplay', 'XUnlockDisplay', 'XInitExtension', 'XAddExtension', 'XFindOnExtensionList', 'XEHeadOfExtensionList', 'XRootWindow', 'XDefaultRootWindow', 'XRootWindowOfScreen', 'XDefaultVisual', 'XDefaultVisualOfScreen', 'XDefaultGC', 'XDefaultGCOfScreen', 'XBlackPixel', 'XWhitePixel', 'XAllPlanes', 'XBlackPixelOfScreen', 'XWhitePixelOfScreen', 'XNextRequest', 'XLastKnownRequestProcessed', 'XServerVendor', 'XDisplayString', 'XDefaultColormap', 'XDefaultColormapOfScreen', 'XDisplayOfScreen', 'XScreenOfDisplay', 'XDefaultScreenOfDisplay', 'XEventMaskOfScreen', 'XScreenNumberOfScreen', 'XErrorHandler', 'XSetErrorHandler', 'XIOErrorHandler', 'XSetIOErrorHandler', 'XListPixmapFormats', 'XListDepths', 'XReconfigureWMWindow', 'XGetWMProtocols', 'XSetWMProtocols', 'XIconifyWindow', 'XWithdrawWindow', 'XGetCommand', 'XGetWMColormapWindows', 'XSetWMColormapWindows', 'XFreeStringList', 'XSetTransientForHint', 'XActivateScreenSaver', 'XAddHost', 'XAddHosts', 'XAddToExtensionList', 'XAddToSaveSet', 'XAllocColor', 'XAllocColorCells', 'XAllocColorPlanes', 'XAllocNamedColor', 'XAllowEvents', 'XAutoRepeatOff', 'XAutoRepeatOn', 'XBell', 'XBitmapBitOrder', 'XBitmapPad', 'XBitmapUnit', 'XCellsOfScreen', 'XChangeActivePointerGrab', 'XChangeGC', 'XChangeKeyboardControl', 'XChangeKeyboardMapping', 'XChangePointerControl', 'XChangeProperty', 'XChangeSaveSet', 'XChangeWindowAttributes', 'XCheckIfEvent', 'XCheckMaskEvent', 'XCheckTypedEvent', 'XCheckTypedWindowEvent', 'XCheckWindowEvent', 'XCirculateSubwindows', 'XCirculateSubwindowsDown', 'XCirculateSubwindowsUp', 'XClearArea', 'XClearWindow', 'XCloseDisplay', 'XConfigureWindow', 'XConnectionNumber', 'XConvertSelection', 'XCopyArea', 'XCopyGC', 'XCopyPlane', 'XDefaultDepth', 'XDefaultDepthOfScreen', 'XDefaultScreen', 'XDefineCursor', 'XDeleteProperty', 'XDestroyWindow', 'XDestroySubwindows', 'XDoesBackingStore', 'XDoesSaveUnders', 'XDisableAccessControl', 'XDisplayCells', 'XDisplayHeight', 'XDisplayHeightMM', 'XDisplayKeycodes', 'XDisplayPlanes', 'XDisplayWidth', 'XDisplayWidthMM', 'XDrawArc', 'XDrawArcs', 'XDrawImageString', 'XDrawImageString16', 'XDrawLine', 'XDrawLines', 'XDrawPoint', 'XDrawPoints', 'XDrawRectangle', 'XDrawRectangles', 'XDrawSegments', 'XDrawString', 'XDrawString16', 'XDrawText', 'XDrawText16', 'XEnableAccessControl', 'XEventsQueued', 'XFetchName', 'XFillArc', 'XFillArcs', 'XFillPolygon', 'XFillRectangle', 'XFillRectangles', 'XFlush', 'XForceScreenSaver', 'XFree', 'XFreeColormap', 'XFreeColors', 'XFreeCursor', 'XFreeExtensionList', 'XFreeFont', 'XFreeFontInfo', 'XFreeFontNames', 'XFreeFontPath', 'XFreeGC', 'XFreeModifiermap', 'XFreePixmap', 'XGeometry', 'XGetErrorDatabaseText', 'XGetErrorText', 'XGetFontProperty', 'XGetGCValues', 'XGetGeometry', 'XGetIconName', 'XGetInputFocus', 'XGetKeyboardControl', 'XGetPointerControl', 'XGetPointerMapping', 'XGetScreenSaver', 'XGetTransientForHint', 'XGetWindowProperty', 'XGetWindowAttributes', 'XGrabButton', 'XGrabKey', 'XGrabKeyboard', 'XGrabPointer', 'XGrabServer', 'XHeightMMOfScreen', 'XHeightOfScreen', 'XIfEvent', 'XImageByteOrder', 'XInstallColormap', 'XKeysymToKeycode', 'XKillClient', 'XLookupColor', 'XLowerWindow', 'XMapRaised', 'XMapSubwindows', 'XMapWindow', 'XMaskEvent', 'XMaxCmapsOfScreen', 'XMinCmapsOfScreen', 'XMoveResizeWindow', 'XMoveWindow', 'XNextEvent', 'XNoOp', 'XParseColor', 'XParseGeometry', 'XPeekEvent', 'XPeekIfEvent', 'XPending', 'XPlanesOfScreen', 'XProtocolRevision', 'XProtocolVersion', 'XPutBackEvent', 'XPutImage', 'XQLength', 'XQueryBestCursor', 'XQueryBestSize', 'XQueryBestStipple', 'XQueryBestTile', 'XQueryColor', 'XQueryColors', 'XQueryExtension', 'XQueryKeymap', 'XQueryPointer', 'XQueryTextExtents', 'XQueryTextExtents16', 'XQueryTree', 'XRaiseWindow', 'XReadBitmapFile', 'XReadBitmapFileData', 'XRebindKeysym', 'XRecolorCursor', 'XRefreshKeyboardMapping', 'XRemoveFromSaveSet', 'XRemoveHost', 'XRemoveHosts', 'XReparentWindow', 'XResetScreenSaver', 'XResizeWindow', 'XRestackWindows', 'XRotateBuffers', 'XRotateWindowProperties', 'XScreenCount', 'XSelectInput', 'XSendEvent', 'XSetAccessControl', 'XSetArcMode', 'XSetBackground', 'XSetClipMask', 'XSetClipOrigin', 'XSetClipRectangles', 'XSetCloseDownMode', 'XSetCommand', 'XSetDashes', 'XSetFillRule', 'XSetFillStyle', 'XSetFont', 'XSetFontPath', 'XSetForeground', 'XSetFunction', 'XSetGraphicsExposures', 'XSetIconName', 'XSetInputFocus', 'XSetLineAttributes', 'XSetModifierMapping', 'XSetPlaneMask', 'XSetPointerMapping', 'XSetScreenSaver', 'XSetSelectionOwner', 'XSetState', 'XSetStipple', 'XSetSubwindowMode', 'XSetTSOrigin', 'XSetTile', 'XSetWindowBackground', 'XSetWindowBackgroundPixmap', 'XSetWindowBorder', 'XSetWindowBorderPixmap', 'XSetWindowBorderWidth', 'XSetWindowColormap', 'XStoreBuffer', 'XStoreBytes', 'XStoreColor', 'XStoreColors', 'XStoreName', 'XStoreNamedColor', 'XSync', 'XTextExtents', 'XTextExtents16', 'XTextWidth', 'XTextWidth16', 'XTranslateCoordinates', 'XUndefineCursor', 'XUngrabButton', 'XUngrabKey', 'XUngrabKeyboard', 'XUngrabPointer', 'XUngrabServer', 'XUninstallColormap', 'XUnloadFont', 'XUnmapSubwindows', 'XUnmapWindow', 'XVendorRelease', 'XWarpPointer', 'XWidthMMOfScreen', 'XWidthOfScreen', 'XWindowEvent', 'XWriteBitmapFile', 'XSupportsLocale', 'XSetLocaleModifiers', 'XOpenOM', 'XCloseOM', 'XSetOMValues', 'XGetOMValues', 'XDisplayOfOM', 'XLocaleOfOM', 'XCreateOC', 'XDestroyOC', 'XOMOfOC', 'XSetOCValues', 'XGetOCValues', 'XCreateFontSet', 'XFreeFontSet', 'XFontsOfFontSet', 'XBaseFontNameListOfFontSet', 'XLocaleOfFontSet', 'XContextDependentDrawing', 'XDirectionalDependentDrawing', 'XContextualDrawing', 'XExtentsOfFontSet', 'XmbTextEscapement', 'XwcTextEscapement', 'Xutf8TextEscapement', 'XmbTextExtents', 'XwcTextExtents', 'Xutf8TextExtents', 'XmbTextPerCharExtents', 'XwcTextPerCharExtents', 'Xutf8TextPerCharExtents', 'XmbDrawText', 'XwcDrawText', 'Xutf8DrawText', 'XmbDrawString', 'XwcDrawString', 'Xutf8DrawString', 'XmbDrawImageString', 'XwcDrawImageString', 'Xutf8DrawImageString', 'XOpenIM', 'XCloseIM', 'XGetIMValues', 'XSetIMValues', 'XDisplayOfIM', 'XLocaleOfIM', 'XCreateIC', 'XDestroyIC', 'XSetICFocus', 'XUnsetICFocus', 'XwcResetIC', 'XmbResetIC', 'Xutf8ResetIC', 'XSetICValues', 'XGetICValues', 'XIMOfIC', 'XFilterEvent', 'XmbLookupString', 'XwcLookupString', 'Xutf8LookupString', 'XVaCreateNestedList', 'XRegisterIMInstantiateCallback', 'XUnregisterIMInstantiateCallback', 'XConnectionWatchProc', 'XInternalConnectionNumbers', 'XProcessInternalConnection', 'XAddConnectionWatch', 'XRemoveConnectionWatch', 'XSetAuthorization', '_Xmbtowc', '_Xwctomb', 'XGetEventData', 'XFreeEventData', 'NoValue', 'XValue', 'YValue', 'WidthValue', 'HeightValue', 'AllValues', 'XNegative', 'YNegative', 'XSizeHints', 'USPosition', 'USSize', 'PPosition', 'PSize', 'PMinSize', 'PMaxSize', 'PResizeInc', 'PAspect', 'PBaseSize', 'PWinGravity', 'PAllHints', 'XWMHints', 'InputHint', 'StateHint', 'IconPixmapHint', 'IconWindowHint', 'IconPositionHint', 'IconMaskHint', 'WindowGroupHint', 'AllHints', 'XUrgencyHint', 'WithdrawnState', 'NormalState', 'IconicState', 'DontCareState', 'ZoomState', 'InactiveState', 'XTextProperty', 'XNoMemory', 'XLocaleNotSupported', 'XConverterNotFound', 'XICCEncodingStyle', 'XStringStyle', 'XCompoundTextStyle', 'XTextStyle', 'XStdICCTextStyle', 'XUTF8StringStyle', 'XIconSize', 'XClassHint', 'XComposeStatus', 'Region', 'RectangleOut', 'RectangleIn', 'RectanglePart', 'XVisualInfo', 'VisualNoMask', 'VisualIDMask', 'VisualScreenMask', 'VisualDepthMask', 'VisualClassMask', 'VisualRedMaskMask', 'VisualGreenMaskMask', 'VisualBlueMaskMask', 'VisualColormapSizeMask', 'VisualBitsPerRGBMask', 'VisualAllMask', 'XStandardColormap', 'BitmapSuccess', 'BitmapOpenFailed', 'BitmapFileInvalid', 'BitmapNoMemory', 'XCSUCCESS', 'XCNOMEM', 'XCNOENT', 'XContext', 'XAllocClassHint', 'XAllocIconSize', 'XAllocSizeHints', 'XAllocStandardColormap', 'XAllocWMHints', 'XClipBox', 'XCreateRegion', 'XDefaultString', 'XDeleteContext', 'XDestroyRegion', 'XEmptyRegion', 'XEqualRegion', 'XFindContext', 'XGetClassHint', 'XGetIconSizes', 'XGetNormalHints', 'XGetRGBColormaps', 'XGetSizeHints', 'XGetStandardColormap', 'XGetTextProperty', 'XGetVisualInfo', 'XGetWMClientMachine', 'XGetWMHints', 'XGetWMIconName', 'XGetWMName', 'XGetWMNormalHints', 'XGetWMSizeHints', 'XGetZoomHints', 'XIntersectRegion', 'XConvertCase', 'XLookupString', 'XMatchVisualInfo', 'XOffsetRegion', 'XPointInRegion', 'XPolygonRegion', 'XRectInRegion', 'XSaveContext', 'XSetClassHint', 'XSetIconSizes', 'XSetNormalHints', 'XSetRGBColormaps', 'XSetSizeHints', 'XSetStandardProperties', 'XSetTextProperty', 'XSetWMClientMachine', 'XSetWMHints', 'XSetWMIconName', 'XSetWMName', 'XSetWMNormalHints', 'XSetWMProperties', 'XmbSetWMProperties', 'Xutf8SetWMProperties', 'XSetWMSizeHints', 'XSetRegion', 'XSetStandardColormap', 'XSetZoomHints', 'XShrinkRegion', 'XStringListToTextProperty', 'XSubtractRegion', 'XmbTextListToTextProperty', 'XwcTextListToTextProperty', 'Xutf8TextListToTextProperty', 'XwcFreeStringList', 'XTextPropertyToStringList', 'XmbTextPropertyToTextList', 'XwcTextPropertyToTextList', 'Xutf8TextPropertyToTextList', 'XUnionRectWithRegion', 'XUnionRegion', 'XWMGeometry', 'XXorRegion']
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' # /usr/include/X11/cursorfont.h XC_num_glyphs = 154 XC_X_cursor = 0 XC_arrow = 2 XC_based_arrow_down = 4 XC_based_arrow_up = 6 XC_boat = 8 XC_bogosity = 10 XC_bottom_left_corner = 12 XC_bottom_right_corner = 14 XC_bottom_side = 16 XC_bottom_tee = 18 XC_box_spiral = 20 XC_center_ptr = 22 XC_circle = 24 XC_clock = 26 XC_coffee_mug = 28 XC_cross = 30 XC_cross_reverse = 32 XC_crosshair = 34 XC_diamond_cross = 36 XC_dot = 38 XC_dotbox = 40 XC_double_arrow = 42 XC_draft_large = 44 XC_draft_small = 46 XC_draped_box = 48 XC_exchange = 50 XC_fleur = 52 XC_gobbler = 54 XC_gumby = 56 XC_hand1 = 58 XC_hand2 = 60 XC_heart = 62 XC_icon = 64 XC_iron_cross = 66 XC_left_ptr = 68 XC_left_side = 70 XC_left_tee = 72 XC_leftbutton = 74 XC_ll_angle = 76 XC_lr_angle = 78 XC_man = 80 XC_middlebutton = 82 XC_mouse = 84 XC_pencil = 86 XC_pirate = 88 XC_plus = 90 XC_question_arrow = 92 XC_right_ptr = 94 XC_right_side = 96 XC_right_tee = 98 XC_rightbutton = 100 XC_rtl_logo = 102 XC_sailboat = 104 XC_sb_down_arrow = 106 XC_sb_h_double_arrow = 108 XC_sb_left_arrow = 110 XC_sb_right_arrow = 112 XC_sb_up_arrow = 114 XC_sb_v_double_arrow = 116 XC_shuttle = 118 XC_sizing = 120 XC_spider = 122 XC_spraycan = 124 XC_star = 126 XC_target = 128 XC_tcross = 130 XC_top_left_arrow = 132 XC_top_left_corner = 134 XC_top_right_corner = 136 XC_top_side = 138 XC_top_tee = 140 XC_trek = 142 XC_ul_angle = 144 XC_umbrella = 146 XC_ur_angle = 148 XC_watch = 150 XC_xterm = 152
Python
'''Wrapper for Xinerama Generated with: tools/genwrappers.py xinerama Do not modify this file. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import ctypes from ctypes import * import pyglet.lib _lib = pyglet.lib.load_library('Xinerama') _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 class struct_anon_93(Structure): __slots__ = [ 'screen_number', 'x_org', 'y_org', 'width', 'height', ] struct_anon_93._fields_ = [ ('screen_number', c_int), ('x_org', c_short), ('y_org', c_short), ('width', c_short), ('height', c_short), ] XineramaScreenInfo = struct_anon_93 # /usr/include/X11/extensions/Xinerama.h:40 Display = pyglet.libs.x11.xlib.Display # /usr/include/X11/extensions/Xinerama.h:44 XineramaQueryExtension = _lib.XineramaQueryExtension XineramaQueryExtension.restype = c_int XineramaQueryExtension.argtypes = [POINTER(Display), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/extensions/Xinerama.h:50 XineramaQueryVersion = _lib.XineramaQueryVersion XineramaQueryVersion.restype = c_int XineramaQueryVersion.argtypes = [POINTER(Display), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/extensions/Xinerama.h:56 XineramaIsActive = _lib.XineramaIsActive XineramaIsActive.restype = c_int XineramaIsActive.argtypes = [POINTER(Display)] # /usr/include/X11/extensions/Xinerama.h:67 XineramaQueryScreens = _lib.XineramaQueryScreens XineramaQueryScreens.restype = POINTER(XineramaScreenInfo) XineramaQueryScreens.argtypes = [POINTER(Display), POINTER(c_int)] __all__ = ['XineramaScreenInfo', 'XineramaQueryExtension', 'XineramaQueryVersion', 'XineramaIsActive', 'XineramaQueryScreens']
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Wrapper for Xext Generated with: tools/genwrappers.py xsync Do not modify this file. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import ctypes from ctypes import * import pyglet.lib _lib = pyglet.lib.load_library('Xext') _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)] # XXX DODGY relative import of xlib.py, which contains XID etc definitions. # can't use wrapped import which gave # import pyglet.window.xlib.xlib # because Python has the lamest import semantics and can't handle that kind of # recursive import, even though it's the same as import xlib SYNC_MAJOR_VERSION = 3 # /usr/include/X11/extensions/sync.h:4901 SYNC_MINOR_VERSION = 0 # /usr/include/X11/extensions/sync.h:4902 X_SyncInitialize = 0 # /usr/include/X11/extensions/sync.h:4904 X_SyncListSystemCounters = 1 # /usr/include/X11/extensions/sync.h:4905 X_SyncCreateCounter = 2 # /usr/include/X11/extensions/sync.h:4906 X_SyncSetCounter = 3 # /usr/include/X11/extensions/sync.h:4907 X_SyncChangeCounter = 4 # /usr/include/X11/extensions/sync.h:4908 X_SyncQueryCounter = 5 # /usr/include/X11/extensions/sync.h:4909 X_SyncDestroyCounter = 6 # /usr/include/X11/extensions/sync.h:4910 X_SyncAwait = 7 # /usr/include/X11/extensions/sync.h:4911 X_SyncCreateAlarm = 8 # /usr/include/X11/extensions/sync.h:4912 X_SyncChangeAlarm = 9 # /usr/include/X11/extensions/sync.h:4913 X_SyncQueryAlarm = 10 # /usr/include/X11/extensions/sync.h:4914 X_SyncDestroyAlarm = 11 # /usr/include/X11/extensions/sync.h:4915 X_SyncSetPriority = 12 # /usr/include/X11/extensions/sync.h:4916 X_SyncGetPriority = 13 # /usr/include/X11/extensions/sync.h:4917 XSyncCounterNotify = 0 # /usr/include/X11/extensions/sync.h:4919 XSyncAlarmNotify = 1 # /usr/include/X11/extensions/sync.h:4920 XSyncAlarmNotifyMask = 2 # /usr/include/X11/extensions/sync.h:4921 XSyncNumberEvents = 2 # /usr/include/X11/extensions/sync.h:4923 XSyncBadCounter = 0 # /usr/include/X11/extensions/sync.h:4925 XSyncBadAlarm = 1 # /usr/include/X11/extensions/sync.h:4926 XSyncNumberErrors = 2 # /usr/include/X11/extensions/sync.h:4927 XSyncCACounter = 1 # /usr/include/X11/extensions/sync.h:4932 XSyncCAValueType = 2 # /usr/include/X11/extensions/sync.h:4933 XSyncCAValue = 4 # /usr/include/X11/extensions/sync.h:4934 XSyncCATestType = 8 # /usr/include/X11/extensions/sync.h:4935 XSyncCADelta = 16 # /usr/include/X11/extensions/sync.h:4936 XSyncCAEvents = 32 # /usr/include/X11/extensions/sync.h:4937 enum_anon_93 = c_int XSyncAbsolute = 0 XSyncRelative = 1 XSyncValueType = enum_anon_93 # /usr/include/X11/extensions/sync.h:4945 enum_anon_94 = c_int XSyncPositiveTransition = 0 XSyncNegativeTransition = 1 XSyncPositiveComparison = 2 XSyncNegativeComparison = 3 XSyncTestType = enum_anon_94 # /usr/include/X11/extensions/sync.h:4955 enum_anon_95 = c_int XSyncAlarmActive = 0 XSyncAlarmInactive = 1 XSyncAlarmDestroyed = 2 XSyncAlarmState = enum_anon_95 # /usr/include/X11/extensions/sync.h:4964 XID = xlib.XID XSyncCounter = XID # /usr/include/X11/extensions/sync.h:4967 XSyncAlarm = XID # /usr/include/X11/extensions/sync.h:4968 class struct__XSyncValue(Structure): __slots__ = [ 'hi', 'lo', ] struct__XSyncValue._fields_ = [ ('hi', c_int), ('lo', c_uint), ] XSyncValue = struct__XSyncValue # /usr/include/X11/extensions/sync.h:4972 # /usr/include/X11/extensions/sync.h:4980 XSyncIntToValue = _lib.XSyncIntToValue XSyncIntToValue.restype = None XSyncIntToValue.argtypes = [POINTER(XSyncValue), c_int] # /usr/include/X11/extensions/sync.h:4985 XSyncIntsToValue = _lib.XSyncIntsToValue XSyncIntsToValue.restype = None XSyncIntsToValue.argtypes = [POINTER(XSyncValue), c_uint, c_int] Bool = xlib.Bool # /usr/include/X11/extensions/sync.h:4991 XSyncValueGreaterThan = _lib.XSyncValueGreaterThan XSyncValueGreaterThan.restype = Bool XSyncValueGreaterThan.argtypes = [XSyncValue, XSyncValue] # /usr/include/X11/extensions/sync.h:4996 XSyncValueLessThan = _lib.XSyncValueLessThan XSyncValueLessThan.restype = Bool XSyncValueLessThan.argtypes = [XSyncValue, XSyncValue] # /usr/include/X11/extensions/sync.h:5001 XSyncValueGreaterOrEqual = _lib.XSyncValueGreaterOrEqual XSyncValueGreaterOrEqual.restype = Bool XSyncValueGreaterOrEqual.argtypes = [XSyncValue, XSyncValue] # /usr/include/X11/extensions/sync.h:5006 XSyncValueLessOrEqual = _lib.XSyncValueLessOrEqual XSyncValueLessOrEqual.restype = Bool XSyncValueLessOrEqual.argtypes = [XSyncValue, XSyncValue] # /usr/include/X11/extensions/sync.h:5011 XSyncValueEqual = _lib.XSyncValueEqual XSyncValueEqual.restype = Bool XSyncValueEqual.argtypes = [XSyncValue, XSyncValue] # /usr/include/X11/extensions/sync.h:5016 XSyncValueIsNegative = _lib.XSyncValueIsNegative XSyncValueIsNegative.restype = Bool XSyncValueIsNegative.argtypes = [XSyncValue] # /usr/include/X11/extensions/sync.h:5020 XSyncValueIsZero = _lib.XSyncValueIsZero XSyncValueIsZero.restype = Bool XSyncValueIsZero.argtypes = [XSyncValue] # /usr/include/X11/extensions/sync.h:5024 XSyncValueIsPositive = _lib.XSyncValueIsPositive XSyncValueIsPositive.restype = Bool XSyncValueIsPositive.argtypes = [XSyncValue] # /usr/include/X11/extensions/sync.h:5028 XSyncValueLow32 = _lib.XSyncValueLow32 XSyncValueLow32.restype = c_uint XSyncValueLow32.argtypes = [XSyncValue] # /usr/include/X11/extensions/sync.h:5032 XSyncValueHigh32 = _lib.XSyncValueHigh32 XSyncValueHigh32.restype = c_int XSyncValueHigh32.argtypes = [XSyncValue] # /usr/include/X11/extensions/sync.h:5036 XSyncValueAdd = _lib.XSyncValueAdd XSyncValueAdd.restype = None XSyncValueAdd.argtypes = [POINTER(XSyncValue), XSyncValue, XSyncValue, POINTER(c_int)] # /usr/include/X11/extensions/sync.h:5043 XSyncValueSubtract = _lib.XSyncValueSubtract XSyncValueSubtract.restype = None XSyncValueSubtract.argtypes = [POINTER(XSyncValue), XSyncValue, XSyncValue, POINTER(c_int)] # /usr/include/X11/extensions/sync.h:5050 XSyncMaxValue = _lib.XSyncMaxValue XSyncMaxValue.restype = None XSyncMaxValue.argtypes = [POINTER(XSyncValue)] # /usr/include/X11/extensions/sync.h:5054 XSyncMinValue = _lib.XSyncMinValue XSyncMinValue.restype = None XSyncMinValue.argtypes = [POINTER(XSyncValue)] class struct__XSyncSystemCounter(Structure): __slots__ = [ 'name', 'counter', 'resolution', ] struct__XSyncSystemCounter._fields_ = [ ('name', c_char_p), ('counter', XSyncCounter), ('resolution', XSyncValue), ] XSyncSystemCounter = struct__XSyncSystemCounter # /usr/include/X11/extensions/sync.h:5131 class struct_anon_96(Structure): __slots__ = [ 'counter', 'value_type', 'wait_value', 'test_type', ] struct_anon_96._fields_ = [ ('counter', XSyncCounter), ('value_type', XSyncValueType), ('wait_value', XSyncValue), ('test_type', XSyncTestType), ] XSyncTrigger = struct_anon_96 # /usr/include/X11/extensions/sync.h:5139 class struct_anon_97(Structure): __slots__ = [ 'trigger', 'event_threshold', ] struct_anon_97._fields_ = [ ('trigger', XSyncTrigger), ('event_threshold', XSyncValue), ] XSyncWaitCondition = struct_anon_97 # /usr/include/X11/extensions/sync.h:5144 class struct_anon_98(Structure): __slots__ = [ 'trigger', 'delta', 'events', 'state', ] struct_anon_98._fields_ = [ ('trigger', XSyncTrigger), ('delta', XSyncValue), ('events', Bool), ('state', XSyncAlarmState), ] XSyncAlarmAttributes = struct_anon_98 # /usr/include/X11/extensions/sync.h:5152 class struct_anon_99(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'counter', 'wait_value', 'counter_value', 'time', 'count', 'destroyed', ] Display = xlib.Display Time = xlib.Time struct_anon_99._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', Bool), ('display', POINTER(Display)), ('counter', XSyncCounter), ('wait_value', XSyncValue), ('counter_value', XSyncValue), ('time', Time), ('count', c_int), ('destroyed', Bool), ] XSyncCounterNotifyEvent = struct_anon_99 # /usr/include/X11/extensions/sync.h:5169 class struct_anon_100(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'alarm', 'counter_value', 'alarm_value', 'time', 'state', ] struct_anon_100._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', Bool), ('display', POINTER(Display)), ('alarm', XSyncAlarm), ('counter_value', XSyncValue), ('alarm_value', XSyncValue), ('time', Time), ('state', XSyncAlarmState), ] XSyncAlarmNotifyEvent = struct_anon_100 # /usr/include/X11/extensions/sync.h:5181 class struct_anon_101(Structure): __slots__ = [ 'type', 'display', 'alarm', 'serial', 'error_code', 'request_code', 'minor_code', ] struct_anon_101._fields_ = [ ('type', c_int), ('display', POINTER(Display)), ('alarm', XSyncAlarm), ('serial', c_ulong), ('error_code', c_ubyte), ('request_code', c_ubyte), ('minor_code', c_ubyte), ] XSyncAlarmError = struct_anon_101 # /usr/include/X11/extensions/sync.h:5195 class struct_anon_102(Structure): __slots__ = [ 'type', 'display', 'counter', 'serial', 'error_code', 'request_code', 'minor_code', ] struct_anon_102._fields_ = [ ('type', c_int), ('display', POINTER(Display)), ('counter', XSyncCounter), ('serial', c_ulong), ('error_code', c_ubyte), ('request_code', c_ubyte), ('minor_code', c_ubyte), ] XSyncCounterError = struct_anon_102 # /usr/include/X11/extensions/sync.h:5205 # /usr/include/X11/extensions/sync.h:5213 XSyncQueryExtension = _lib.XSyncQueryExtension XSyncQueryExtension.restype = c_int XSyncQueryExtension.argtypes = [POINTER(Display), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/extensions/sync.h:5219 XSyncInitialize = _lib.XSyncInitialize XSyncInitialize.restype = c_int XSyncInitialize.argtypes = [POINTER(Display), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/extensions/sync.h:5225 XSyncListSystemCounters = _lib.XSyncListSystemCounters XSyncListSystemCounters.restype = POINTER(XSyncSystemCounter) XSyncListSystemCounters.argtypes = [POINTER(Display), POINTER(c_int)] # /usr/include/X11/extensions/sync.h:5230 XSyncFreeSystemCounterList = _lib.XSyncFreeSystemCounterList XSyncFreeSystemCounterList.restype = None XSyncFreeSystemCounterList.argtypes = [POINTER(XSyncSystemCounter)] # /usr/include/X11/extensions/sync.h:5234 XSyncCreateCounter = _lib.XSyncCreateCounter XSyncCreateCounter.restype = XSyncCounter XSyncCreateCounter.argtypes = [POINTER(Display), XSyncValue] # /usr/include/X11/extensions/sync.h:5239 XSyncSetCounter = _lib.XSyncSetCounter XSyncSetCounter.restype = c_int XSyncSetCounter.argtypes = [POINTER(Display), XSyncCounter, XSyncValue] # /usr/include/X11/extensions/sync.h:5245 XSyncChangeCounter = _lib.XSyncChangeCounter XSyncChangeCounter.restype = c_int XSyncChangeCounter.argtypes = [POINTER(Display), XSyncCounter, XSyncValue] # /usr/include/X11/extensions/sync.h:5251 XSyncDestroyCounter = _lib.XSyncDestroyCounter XSyncDestroyCounter.restype = c_int XSyncDestroyCounter.argtypes = [POINTER(Display), XSyncCounter] # /usr/include/X11/extensions/sync.h:5256 XSyncQueryCounter = _lib.XSyncQueryCounter XSyncQueryCounter.restype = c_int XSyncQueryCounter.argtypes = [POINTER(Display), XSyncCounter, POINTER(XSyncValue)] # /usr/include/X11/extensions/sync.h:5262 XSyncAwait = _lib.XSyncAwait XSyncAwait.restype = c_int XSyncAwait.argtypes = [POINTER(Display), POINTER(XSyncWaitCondition), c_int] # /usr/include/X11/extensions/sync.h:5268 XSyncCreateAlarm = _lib.XSyncCreateAlarm XSyncCreateAlarm.restype = XSyncAlarm XSyncCreateAlarm.argtypes = [POINTER(Display), c_ulong, POINTER(XSyncAlarmAttributes)] # /usr/include/X11/extensions/sync.h:5274 XSyncDestroyAlarm = _lib.XSyncDestroyAlarm XSyncDestroyAlarm.restype = c_int XSyncDestroyAlarm.argtypes = [POINTER(Display), XSyncAlarm] # /usr/include/X11/extensions/sync.h:5279 XSyncQueryAlarm = _lib.XSyncQueryAlarm XSyncQueryAlarm.restype = c_int XSyncQueryAlarm.argtypes = [POINTER(Display), XSyncAlarm, POINTER(XSyncAlarmAttributes)] # /usr/include/X11/extensions/sync.h:5285 XSyncChangeAlarm = _lib.XSyncChangeAlarm XSyncChangeAlarm.restype = c_int XSyncChangeAlarm.argtypes = [POINTER(Display), XSyncAlarm, c_ulong, POINTER(XSyncAlarmAttributes)] # /usr/include/X11/extensions/sync.h:5292 XSyncSetPriority = _lib.XSyncSetPriority XSyncSetPriority.restype = c_int XSyncSetPriority.argtypes = [POINTER(Display), XID, c_int] # /usr/include/X11/extensions/sync.h:5298 XSyncGetPriority = _lib.XSyncGetPriority XSyncGetPriority.restype = c_int XSyncGetPriority.argtypes = [POINTER(Display), XID, POINTER(c_int)] __all__ = ['SYNC_MAJOR_VERSION', 'SYNC_MINOR_VERSION', 'X_SyncInitialize', 'X_SyncListSystemCounters', 'X_SyncCreateCounter', 'X_SyncSetCounter', 'X_SyncChangeCounter', 'X_SyncQueryCounter', 'X_SyncDestroyCounter', 'X_SyncAwait', 'X_SyncCreateAlarm', 'X_SyncChangeAlarm', 'X_SyncQueryAlarm', 'X_SyncDestroyAlarm', 'X_SyncSetPriority', 'X_SyncGetPriority', 'XSyncCounterNotify', 'XSyncAlarmNotify', 'XSyncAlarmNotifyMask', 'XSyncNumberEvents', 'XSyncBadCounter', 'XSyncBadAlarm', 'XSyncNumberErrors', 'XSyncCACounter', 'XSyncCAValueType', 'XSyncCAValue', 'XSyncCATestType', 'XSyncCADelta', 'XSyncCAEvents', 'XSyncValueType', 'XSyncAbsolute', 'XSyncRelative', 'XSyncTestType', 'XSyncPositiveTransition', 'XSyncNegativeTransition', 'XSyncPositiveComparison', 'XSyncNegativeComparison', 'XSyncAlarmState', 'XSyncAlarmActive', 'XSyncAlarmInactive', 'XSyncAlarmDestroyed', 'XSyncCounter', 'XSyncAlarm', 'XSyncValue', 'XSyncIntToValue', 'XSyncIntsToValue', 'XSyncValueGreaterThan', 'XSyncValueLessThan', 'XSyncValueGreaterOrEqual', 'XSyncValueLessOrEqual', 'XSyncValueEqual', 'XSyncValueIsNegative', 'XSyncValueIsZero', 'XSyncValueIsPositive', 'XSyncValueLow32', 'XSyncValueHigh32', 'XSyncValueAdd', 'XSyncValueSubtract', 'XSyncMaxValue', 'XSyncMinValue', 'XSyncSystemCounter', 'XSyncTrigger', 'XSyncWaitCondition', 'XSyncAlarmAttributes', 'XSyncCounterNotifyEvent', 'XSyncAlarmNotifyEvent', 'XSyncAlarmError', 'XSyncCounterError', 'XSyncQueryExtension', 'XSyncInitialize', 'XSyncListSystemCounters', 'XSyncFreeSystemCounterList', 'XSyncCreateCounter', 'XSyncSetCounter', 'XSyncChangeCounter', 'XSyncDestroyCounter', 'XSyncQueryCounter', 'XSyncAwait', 'XSyncCreateAlarm', 'XSyncDestroyAlarm', 'XSyncQueryAlarm', 'XSyncChangeAlarm', 'XSyncSetPriority', 'XSyncGetPriority']
Python
'''Wrapper for Xxf86vm Generated with: tools/genwrappers.py xf86vmode Do not modify this file. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import ctypes from ctypes import * import pyglet.lib _lib = pyglet.lib.load_library('Xxf86vm') _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 X_XF86VidModeQueryVersion = 0 # /usr/include/X11/extensions/xf86vmode.h:4885 X_XF86VidModeGetModeLine = 1 # /usr/include/X11/extensions/xf86vmode.h:4886 X_XF86VidModeModModeLine = 2 # /usr/include/X11/extensions/xf86vmode.h:4887 X_XF86VidModeSwitchMode = 3 # /usr/include/X11/extensions/xf86vmode.h:4888 X_XF86VidModeGetMonitor = 4 # /usr/include/X11/extensions/xf86vmode.h:4889 X_XF86VidModeLockModeSwitch = 5 # /usr/include/X11/extensions/xf86vmode.h:4890 X_XF86VidModeGetAllModeLines = 6 # /usr/include/X11/extensions/xf86vmode.h:4891 X_XF86VidModeAddModeLine = 7 # /usr/include/X11/extensions/xf86vmode.h:4892 X_XF86VidModeDeleteModeLine = 8 # /usr/include/X11/extensions/xf86vmode.h:4893 X_XF86VidModeValidateModeLine = 9 # /usr/include/X11/extensions/xf86vmode.h:4894 X_XF86VidModeSwitchToMode = 10 # /usr/include/X11/extensions/xf86vmode.h:4895 X_XF86VidModeGetViewPort = 11 # /usr/include/X11/extensions/xf86vmode.h:4896 X_XF86VidModeSetViewPort = 12 # /usr/include/X11/extensions/xf86vmode.h:4897 X_XF86VidModeGetDotClocks = 13 # /usr/include/X11/extensions/xf86vmode.h:4899 X_XF86VidModeSetClientVersion = 14 # /usr/include/X11/extensions/xf86vmode.h:4900 X_XF86VidModeSetGamma = 15 # /usr/include/X11/extensions/xf86vmode.h:4901 X_XF86VidModeGetGamma = 16 # /usr/include/X11/extensions/xf86vmode.h:4902 X_XF86VidModeGetGammaRamp = 17 # /usr/include/X11/extensions/xf86vmode.h:4903 X_XF86VidModeSetGammaRamp = 18 # /usr/include/X11/extensions/xf86vmode.h:4904 X_XF86VidModeGetGammaRampSize = 19 # /usr/include/X11/extensions/xf86vmode.h:4905 X_XF86VidModeGetPermissions = 20 # /usr/include/X11/extensions/xf86vmode.h:4906 CLKFLAG_PROGRAMABLE = 1 # /usr/include/X11/extensions/xf86vmode.h:4908 XF86VidModeNumberEvents = 0 # /usr/include/X11/extensions/xf86vmode.h:4919 XF86VidModeBadClock = 0 # /usr/include/X11/extensions/xf86vmode.h:4922 XF86VidModeBadHTimings = 1 # /usr/include/X11/extensions/xf86vmode.h:4923 XF86VidModeBadVTimings = 2 # /usr/include/X11/extensions/xf86vmode.h:4924 XF86VidModeModeUnsuitable = 3 # /usr/include/X11/extensions/xf86vmode.h:4925 XF86VidModeExtensionDisabled = 4 # /usr/include/X11/extensions/xf86vmode.h:4926 XF86VidModeClientNotLocal = 5 # /usr/include/X11/extensions/xf86vmode.h:4927 XF86VidModeZoomLocked = 6 # /usr/include/X11/extensions/xf86vmode.h:4928 XF86VidModeNumberErrors = 7 # /usr/include/X11/extensions/xf86vmode.h:4929 XF86VM_READ_PERMISSION = 1 # /usr/include/X11/extensions/xf86vmode.h:4931 XF86VM_WRITE_PERMISSION = 2 # /usr/include/X11/extensions/xf86vmode.h:4932 class struct_anon_93(Structure): __slots__ = [ 'hdisplay', 'hsyncstart', 'hsyncend', 'htotal', 'hskew', 'vdisplay', 'vsyncstart', 'vsyncend', 'vtotal', 'flags', 'privsize', 'private', ] INT32 = c_int # /usr/include/X11/Xmd.h:135 struct_anon_93._fields_ = [ ('hdisplay', c_ushort), ('hsyncstart', c_ushort), ('hsyncend', c_ushort), ('htotal', c_ushort), ('hskew', c_ushort), ('vdisplay', c_ushort), ('vsyncstart', c_ushort), ('vsyncend', c_ushort), ('vtotal', c_ushort), ('flags', c_uint), ('privsize', c_int), ('private', POINTER(INT32)), ] XF86VidModeModeLine = struct_anon_93 # /usr/include/X11/extensions/xf86vmode.h:4954 class struct_anon_94(Structure): __slots__ = [ 'dotclock', 'hdisplay', 'hsyncstart', 'hsyncend', 'htotal', 'hskew', 'vdisplay', 'vsyncstart', 'vsyncend', 'vtotal', 'flags', 'privsize', 'private', ] struct_anon_94._fields_ = [ ('dotclock', c_uint), ('hdisplay', c_ushort), ('hsyncstart', c_ushort), ('hsyncend', c_ushort), ('htotal', c_ushort), ('hskew', c_ushort), ('vdisplay', c_ushort), ('vsyncstart', c_ushort), ('vsyncend', c_ushort), ('vtotal', c_ushort), ('flags', c_uint), ('privsize', c_int), ('private', POINTER(INT32)), ] XF86VidModeModeInfo = struct_anon_94 # /usr/include/X11/extensions/xf86vmode.h:4975 class struct_anon_95(Structure): __slots__ = [ 'hi', 'lo', ] struct_anon_95._fields_ = [ ('hi', c_float), ('lo', c_float), ] XF86VidModeSyncRange = struct_anon_95 # /usr/include/X11/extensions/xf86vmode.h:4980 class struct_anon_96(Structure): __slots__ = [ 'vendor', 'model', 'EMPTY', 'nhsync', 'hsync', 'nvsync', 'vsync', ] struct_anon_96._fields_ = [ ('vendor', c_char_p), ('model', c_char_p), ('EMPTY', c_float), ('nhsync', c_ubyte), ('hsync', POINTER(XF86VidModeSyncRange)), ('nvsync', c_ubyte), ('vsync', POINTER(XF86VidModeSyncRange)), ] XF86VidModeMonitor = struct_anon_96 # /usr/include/X11/extensions/xf86vmode.h:4990 class struct_anon_97(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'root', 'state', 'kind', 'forced', 'time', ] Display = pyglet.libs.x11.xlib.Display Window = pyglet.libs.x11.xlib.Window Time = pyglet.libs.x11.xlib.Time struct_anon_97._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('root', Window), ('state', c_int), ('kind', c_int), ('forced', c_int), ('time', Time), ] XF86VidModeNotifyEvent = struct_anon_97 # /usr/include/X11/extensions/xf86vmode.h:5002 class struct_anon_98(Structure): __slots__ = [ 'red', 'green', 'blue', ] struct_anon_98._fields_ = [ ('red', c_float), ('green', c_float), ('blue', c_float), ] XF86VidModeGamma = struct_anon_98 # /usr/include/X11/extensions/xf86vmode.h:5008 # /usr/include/X11/extensions/xf86vmode.h:5018 XF86VidModeQueryVersion = _lib.XF86VidModeQueryVersion XF86VidModeQueryVersion.restype = c_int XF86VidModeQueryVersion.argtypes = [POINTER(Display), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/extensions/xf86vmode.h:5024 XF86VidModeQueryExtension = _lib.XF86VidModeQueryExtension XF86VidModeQueryExtension.restype = c_int XF86VidModeQueryExtension.argtypes = [POINTER(Display), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/extensions/xf86vmode.h:5030 XF86VidModeSetClientVersion = _lib.XF86VidModeSetClientVersion XF86VidModeSetClientVersion.restype = c_int XF86VidModeSetClientVersion.argtypes = [POINTER(Display)] # /usr/include/X11/extensions/xf86vmode.h:5034 XF86VidModeGetModeLine = _lib.XF86VidModeGetModeLine XF86VidModeGetModeLine.restype = c_int XF86VidModeGetModeLine.argtypes = [POINTER(Display), c_int, POINTER(c_int), POINTER(XF86VidModeModeLine)] # /usr/include/X11/extensions/xf86vmode.h:5041 XF86VidModeGetAllModeLines = _lib.XF86VidModeGetAllModeLines XF86VidModeGetAllModeLines.restype = c_int XF86VidModeGetAllModeLines.argtypes = [POINTER(Display), c_int, POINTER(c_int), POINTER(POINTER(POINTER(XF86VidModeModeInfo)))] # /usr/include/X11/extensions/xf86vmode.h:5048 XF86VidModeAddModeLine = _lib.XF86VidModeAddModeLine XF86VidModeAddModeLine.restype = c_int XF86VidModeAddModeLine.argtypes = [POINTER(Display), c_int, POINTER(XF86VidModeModeInfo), POINTER(XF86VidModeModeInfo)] # /usr/include/X11/extensions/xf86vmode.h:5055 XF86VidModeDeleteModeLine = _lib.XF86VidModeDeleteModeLine XF86VidModeDeleteModeLine.restype = c_int XF86VidModeDeleteModeLine.argtypes = [POINTER(Display), c_int, POINTER(XF86VidModeModeInfo)] # /usr/include/X11/extensions/xf86vmode.h:5061 XF86VidModeModModeLine = _lib.XF86VidModeModModeLine XF86VidModeModModeLine.restype = c_int XF86VidModeModModeLine.argtypes = [POINTER(Display), c_int, POINTER(XF86VidModeModeLine)] # /usr/include/X11/extensions/xf86vmode.h:5067 XF86VidModeValidateModeLine = _lib.XF86VidModeValidateModeLine XF86VidModeValidateModeLine.restype = c_int XF86VidModeValidateModeLine.argtypes = [POINTER(Display), c_int, POINTER(XF86VidModeModeInfo)] # /usr/include/X11/extensions/xf86vmode.h:5073 XF86VidModeSwitchMode = _lib.XF86VidModeSwitchMode XF86VidModeSwitchMode.restype = c_int XF86VidModeSwitchMode.argtypes = [POINTER(Display), c_int, c_int] # /usr/include/X11/extensions/xf86vmode.h:5079 XF86VidModeSwitchToMode = _lib.XF86VidModeSwitchToMode XF86VidModeSwitchToMode.restype = c_int XF86VidModeSwitchToMode.argtypes = [POINTER(Display), c_int, POINTER(XF86VidModeModeInfo)] # /usr/include/X11/extensions/xf86vmode.h:5085 XF86VidModeLockModeSwitch = _lib.XF86VidModeLockModeSwitch XF86VidModeLockModeSwitch.restype = c_int XF86VidModeLockModeSwitch.argtypes = [POINTER(Display), c_int, c_int] # /usr/include/X11/extensions/xf86vmode.h:5091 XF86VidModeGetMonitor = _lib.XF86VidModeGetMonitor XF86VidModeGetMonitor.restype = c_int XF86VidModeGetMonitor.argtypes = [POINTER(Display), c_int, POINTER(XF86VidModeMonitor)] # /usr/include/X11/extensions/xf86vmode.h:5097 XF86VidModeGetViewPort = _lib.XF86VidModeGetViewPort XF86VidModeGetViewPort.restype = c_int XF86VidModeGetViewPort.argtypes = [POINTER(Display), c_int, POINTER(c_int), POINTER(c_int)] # /usr/include/X11/extensions/xf86vmode.h:5104 XF86VidModeSetViewPort = _lib.XF86VidModeSetViewPort XF86VidModeSetViewPort.restype = c_int XF86VidModeSetViewPort.argtypes = [POINTER(Display), c_int, c_int, c_int] # /usr/include/X11/extensions/xf86vmode.h:5111 XF86VidModeGetDotClocks = _lib.XF86VidModeGetDotClocks XF86VidModeGetDotClocks.restype = c_int XF86VidModeGetDotClocks.argtypes = [POINTER(Display), c_int, POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(POINTER(c_int))] # /usr/include/X11/extensions/xf86vmode.h:5120 XF86VidModeGetGamma = _lib.XF86VidModeGetGamma XF86VidModeGetGamma.restype = c_int XF86VidModeGetGamma.argtypes = [POINTER(Display), c_int, POINTER(XF86VidModeGamma)] # /usr/include/X11/extensions/xf86vmode.h:5126 XF86VidModeSetGamma = _lib.XF86VidModeSetGamma XF86VidModeSetGamma.restype = c_int XF86VidModeSetGamma.argtypes = [POINTER(Display), c_int, POINTER(XF86VidModeGamma)] # /usr/include/X11/extensions/xf86vmode.h:5132 XF86VidModeSetGammaRamp = _lib.XF86VidModeSetGammaRamp XF86VidModeSetGammaRamp.restype = c_int XF86VidModeSetGammaRamp.argtypes = [POINTER(Display), c_int, c_int, POINTER(c_ushort), POINTER(c_ushort), POINTER(c_ushort)] # /usr/include/X11/extensions/xf86vmode.h:5141 XF86VidModeGetGammaRamp = _lib.XF86VidModeGetGammaRamp XF86VidModeGetGammaRamp.restype = c_int XF86VidModeGetGammaRamp.argtypes = [POINTER(Display), c_int, c_int, POINTER(c_ushort), POINTER(c_ushort), POINTER(c_ushort)] # /usr/include/X11/extensions/xf86vmode.h:5150 XF86VidModeGetGammaRampSize = _lib.XF86VidModeGetGammaRampSize XF86VidModeGetGammaRampSize.restype = c_int XF86VidModeGetGammaRampSize.argtypes = [POINTER(Display), c_int, POINTER(c_int)] # /usr/include/X11/extensions/xf86vmode.h:5156 XF86VidModeGetPermissions = _lib.XF86VidModeGetPermissions XF86VidModeGetPermissions.restype = c_int XF86VidModeGetPermissions.argtypes = [POINTER(Display), c_int, POINTER(c_int)] __all__ = ['X_XF86VidModeQueryVersion', 'X_XF86VidModeGetModeLine', 'X_XF86VidModeModModeLine', 'X_XF86VidModeSwitchMode', 'X_XF86VidModeGetMonitor', 'X_XF86VidModeLockModeSwitch', 'X_XF86VidModeGetAllModeLines', 'X_XF86VidModeAddModeLine', 'X_XF86VidModeDeleteModeLine', 'X_XF86VidModeValidateModeLine', 'X_XF86VidModeSwitchToMode', 'X_XF86VidModeGetViewPort', 'X_XF86VidModeSetViewPort', 'X_XF86VidModeGetDotClocks', 'X_XF86VidModeSetClientVersion', 'X_XF86VidModeSetGamma', 'X_XF86VidModeGetGamma', 'X_XF86VidModeGetGammaRamp', 'X_XF86VidModeSetGammaRamp', 'X_XF86VidModeGetGammaRampSize', 'X_XF86VidModeGetPermissions', 'CLKFLAG_PROGRAMABLE', 'XF86VidModeNumberEvents', 'XF86VidModeBadClock', 'XF86VidModeBadHTimings', 'XF86VidModeBadVTimings', 'XF86VidModeModeUnsuitable', 'XF86VidModeExtensionDisabled', 'XF86VidModeClientNotLocal', 'XF86VidModeZoomLocked', 'XF86VidModeNumberErrors', 'XF86VM_READ_PERMISSION', 'XF86VM_WRITE_PERMISSION', 'XF86VidModeModeLine', 'XF86VidModeModeInfo', 'XF86VidModeSyncRange', 'XF86VidModeMonitor', 'XF86VidModeNotifyEvent', 'XF86VidModeGamma', 'XF86VidModeQueryVersion', 'XF86VidModeQueryExtension', 'XF86VidModeSetClientVersion', 'XF86VidModeGetModeLine', 'XF86VidModeGetAllModeLines', 'XF86VidModeAddModeLine', 'XF86VidModeDeleteModeLine', 'XF86VidModeModModeLine', 'XF86VidModeValidateModeLine', 'XF86VidModeSwitchMode', 'XF86VidModeSwitchToMode', 'XF86VidModeLockModeSwitch', 'XF86VidModeGetMonitor', 'XF86VidModeGetViewPort', 'XF86VidModeSetViewPort', 'XF86VidModeGetDotClocks', 'XF86VidModeGetGamma', 'XF86VidModeSetGamma', 'XF86VidModeSetGammaRamp', 'XF86VidModeGetGammaRamp', 'XF86VidModeGetGammaRampSize', 'XF86VidModeGetPermissions']
Python
'''Wrapper for Xi Generated with: tools/genwrappers.py xinput Do not modify this file. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: wrap.py 1694 2008-01-30 23:12:00Z Alex.Holkner $' import ctypes from ctypes import * import pyglet.lib _lib = pyglet.lib.load_library('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_93(Structure): __slots__ = [ 'present', 'major_version', 'minor_version', ] struct_anon_93._fields_ = [ ('present', c_int), ('major_version', c_short), ('minor_version', c_short), ] XExtensionVersion = struct_anon_93 # /usr/include/X11/extensions/XI.h:285 _deviceKeyPress = 0 # /usr/include/X11/extensions/XInput.h:4902 _deviceKeyRelease = 1 # /usr/include/X11/extensions/XInput.h:4903 _deviceButtonPress = 0 # /usr/include/X11/extensions/XInput.h:4905 _deviceButtonRelease = 1 # /usr/include/X11/extensions/XInput.h:4906 _deviceMotionNotify = 0 # /usr/include/X11/extensions/XInput.h:4908 _deviceFocusIn = 0 # /usr/include/X11/extensions/XInput.h:4910 _deviceFocusOut = 1 # /usr/include/X11/extensions/XInput.h:4911 _proximityIn = 0 # /usr/include/X11/extensions/XInput.h:4913 _proximityOut = 1 # /usr/include/X11/extensions/XInput.h:4914 _deviceStateNotify = 0 # /usr/include/X11/extensions/XInput.h:4916 _deviceMappingNotify = 1 # /usr/include/X11/extensions/XInput.h:4917 _changeDeviceNotify = 2 # /usr/include/X11/extensions/XInput.h:4918 class struct_anon_94(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.libs.x11.xlib.Display Window = pyglet.libs.x11.xlib.Window XID = pyglet.libs.x11.xlib.XID Time = pyglet.libs.x11.xlib.Time struct_anon_94._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_94 # /usr/include/X11/extensions/XInput.h:5043 XDeviceKeyPressedEvent = XDeviceKeyEvent # /usr/include/X11/extensions/XInput.h:5045 XDeviceKeyReleasedEvent = XDeviceKeyEvent # /usr/include/X11/extensions/XInput.h:5046 class struct_anon_95(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_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), ('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_95 # /usr/include/X11/extensions/XInput.h:5075 XDeviceButtonPressedEvent = XDeviceButtonEvent # /usr/include/X11/extensions/XInput.h:5077 XDeviceButtonReleasedEvent = XDeviceButtonEvent # /usr/include/X11/extensions/XInput.h:5078 class struct_anon_96(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_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), ('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_96 # /usr/include/X11/extensions/XInput.h:5108 class struct_anon_97(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'deviceid', 'mode', 'detail', 'time', ] struct_anon_97._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_97 # /usr/include/X11/extensions/XInput.h:5133 XDeviceFocusInEvent = XDeviceFocusChangeEvent # /usr/include/X11/extensions/XInput.h:5135 XDeviceFocusOutEvent = XDeviceFocusChangeEvent # /usr/include/X11/extensions/XInput.h:5136 class struct_anon_98(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_98._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_98 # /usr/include/X11/extensions/XInput.h:5164 XProximityInEvent = XProximityNotifyEvent # /usr/include/X11/extensions/XInput.h:5165 XProximityOutEvent = XProximityNotifyEvent # /usr/include/X11/extensions/XInput.h:5166 class struct_anon_99(Structure): __slots__ = [ 'class', 'length', ] struct_anon_99._fields_ = [ ('class', c_ubyte), ('length', c_ubyte), ] XInputClass = struct_anon_99 # /usr/include/X11/extensions/XInput.h:5183 class struct_anon_100(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'deviceid', 'time', 'num_classes', 'data', ] struct_anon_100._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_100 # /usr/include/X11/extensions/XInput.h:5195 class struct_anon_101(Structure): __slots__ = [ 'class', 'length', 'num_valuators', 'mode', 'valuators', ] struct_anon_101._fields_ = [ ('class', c_ubyte), ('length', c_ubyte), ('num_valuators', c_ubyte), ('mode', c_ubyte), ('valuators', c_int * 6), ] XValuatorStatus = struct_anon_101 # /usr/include/X11/extensions/XInput.h:5207 class struct_anon_102(Structure): __slots__ = [ 'class', 'length', 'num_keys', 'keys', ] struct_anon_102._fields_ = [ ('class', c_ubyte), ('length', c_ubyte), ('num_keys', c_short), ('keys', c_char * 32), ] XKeyStatus = struct_anon_102 # /usr/include/X11/extensions/XInput.h:5218 class struct_anon_103(Structure): __slots__ = [ 'class', 'length', 'num_buttons', 'buttons', ] struct_anon_103._fields_ = [ ('class', c_ubyte), ('length', c_ubyte), ('num_buttons', c_short), ('buttons', c_char * 32), ] XButtonStatus = struct_anon_103 # /usr/include/X11/extensions/XInput.h:5229 class struct_anon_104(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'deviceid', 'time', 'request', 'first_keycode', 'count', ] struct_anon_104._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_104 # /usr/include/X11/extensions/XInput.h:5250 class struct_anon_105(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'deviceid', 'time', 'request', ] 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), ] XChangeDeviceNotifyEvent = struct_anon_105 # /usr/include/X11/extensions/XInput.h:5268 class struct_anon_106(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'time', 'devchange', 'deviceid', 'control', ] struct_anon_106._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_106 # /usr/include/X11/extensions/XInput.h:5293 class struct_anon_107(Structure): __slots__ = [ 'class', 'length', 'id', ] struct_anon_107._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ] XFeedbackState = struct_anon_107 # /usr/include/X11/extensions/XInput.h:5311 class struct_anon_108(Structure): __slots__ = [ 'class', 'length', 'id', 'click', 'percent', 'pitch', 'duration', 'led_mask', 'global_auto_repeat', 'auto_repeats', ] struct_anon_108._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_108 # /usr/include/X11/extensions/XInput.h:5328 class struct_anon_109(Structure): __slots__ = [ 'class', 'length', 'id', 'accelNum', 'accelDenom', 'threshold', ] struct_anon_109._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('accelNum', c_int), ('accelDenom', c_int), ('threshold', c_int), ] XPtrFeedbackState = struct_anon_109 # /usr/include/X11/extensions/XInput.h:5341 class struct_anon_110(Structure): __slots__ = [ 'class', 'length', 'id', 'resolution', 'minVal', 'maxVal', ] struct_anon_110._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('resolution', c_int), ('minVal', c_int), ('maxVal', c_int), ] XIntegerFeedbackState = struct_anon_110 # /usr/include/X11/extensions/XInput.h:5354 class struct_anon_111(Structure): __slots__ = [ 'class', 'length', 'id', 'max_symbols', 'num_syms_supported', 'syms_supported', ] KeySym = pyglet.libs.x11.xlib.KeySym struct_anon_111._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('max_symbols', c_int), ('num_syms_supported', c_int), ('syms_supported', POINTER(KeySym)), ] XStringFeedbackState = struct_anon_111 # /usr/include/X11/extensions/XInput.h:5367 class struct_anon_112(Structure): __slots__ = [ 'class', 'length', 'id', 'percent', 'pitch', 'duration', ] struct_anon_112._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('percent', c_int), ('pitch', c_int), ('duration', c_int), ] XBellFeedbackState = struct_anon_112 # /usr/include/X11/extensions/XInput.h:5380 class struct_anon_113(Structure): __slots__ = [ 'class', 'length', 'id', 'led_values', 'led_mask', ] struct_anon_113._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('led_values', c_int), ('led_mask', c_int), ] XLedFeedbackState = struct_anon_113 # /usr/include/X11/extensions/XInput.h:5392 class struct_anon_114(Structure): __slots__ = [ 'class', 'length', 'id', ] struct_anon_114._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ] XFeedbackControl = struct_anon_114 # /usr/include/X11/extensions/XInput.h:5402 class struct_anon_115(Structure): __slots__ = [ 'class', 'length', 'id', 'accelNum', 'accelDenom', 'threshold', ] struct_anon_115._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('accelNum', c_int), ('accelDenom', c_int), ('threshold', c_int), ] XPtrFeedbackControl = struct_anon_115 # /usr/include/X11/extensions/XInput.h:5415 class struct_anon_116(Structure): __slots__ = [ 'class', 'length', 'id', 'click', 'percent', 'pitch', 'duration', 'led_mask', 'led_value', 'key', 'auto_repeat_mode', ] struct_anon_116._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_116 # /usr/include/X11/extensions/XInput.h:5433 class struct_anon_117(Structure): __slots__ = [ 'class', 'length', 'id', 'num_keysyms', 'syms_to_display', ] struct_anon_117._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('num_keysyms', c_int), ('syms_to_display', POINTER(KeySym)), ] XStringFeedbackControl = struct_anon_117 # /usr/include/X11/extensions/XInput.h:5445 class struct_anon_118(Structure): __slots__ = [ 'class', 'length', 'id', 'int_to_display', ] struct_anon_118._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('int_to_display', c_int), ] XIntegerFeedbackControl = struct_anon_118 # /usr/include/X11/extensions/XInput.h:5456 class struct_anon_119(Structure): __slots__ = [ 'class', 'length', 'id', 'percent', 'pitch', 'duration', ] struct_anon_119._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('percent', c_int), ('pitch', c_int), ('duration', c_int), ] XBellFeedbackControl = struct_anon_119 # /usr/include/X11/extensions/XInput.h:5469 class struct_anon_120(Structure): __slots__ = [ 'class', 'length', 'id', 'led_mask', 'led_values', ] struct_anon_120._fields_ = [ ('class', XID), ('length', c_int), ('id', XID), ('led_mask', c_int), ('led_values', c_int), ] XLedFeedbackControl = struct_anon_120 # /usr/include/X11/extensions/XInput.h:5481 class struct_anon_121(Structure): __slots__ = [ 'control', 'length', ] struct_anon_121._fields_ = [ ('control', XID), ('length', c_int), ] XDeviceControl = struct_anon_121 # /usr/include/X11/extensions/XInput.h:5492 class struct_anon_122(Structure): __slots__ = [ 'control', 'length', 'first_valuator', 'num_valuators', 'resolutions', ] struct_anon_122._fields_ = [ ('control', XID), ('length', c_int), ('first_valuator', c_int), ('num_valuators', c_int), ('resolutions', POINTER(c_int)), ] XDeviceResolutionControl = struct_anon_122 # /usr/include/X11/extensions/XInput.h:5500 class struct_anon_123(Structure): __slots__ = [ 'control', 'length', 'num_valuators', 'resolutions', 'min_resolutions', 'max_resolutions', ] struct_anon_123._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_123 # /usr/include/X11/extensions/XInput.h:5509 class struct_anon_124(Structure): __slots__ = [ 'control', 'length', 'min_x', 'max_x', 'min_y', 'max_y', 'flip_x', 'flip_y', 'rotation', 'button_threshold', ] struct_anon_124._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_124 # /usr/include/X11/extensions/XInput.h:5522 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), ] XDeviceAbsCalibState = struct_anon_125 # /usr/include/X11/extensions/XInput.h:5522 class struct_anon_126(Structure): __slots__ = [ 'control', 'length', 'offset_x', 'offset_y', 'width', 'height', 'screen', 'following', ] struct_anon_126._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_126 # /usr/include/X11/extensions/XInput.h:5533 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), ] XDeviceAbsAreaState = struct_anon_127 # /usr/include/X11/extensions/XInput.h:5533 class struct_anon_128(Structure): __slots__ = [ 'control', 'length', 'status', ] struct_anon_128._fields_ = [ ('control', XID), ('length', c_int), ('status', c_int), ] XDeviceCoreControl = struct_anon_128 # /usr/include/X11/extensions/XInput.h:5539 class struct_anon_129(Structure): __slots__ = [ 'control', 'length', 'status', 'iscore', ] struct_anon_129._fields_ = [ ('control', XID), ('length', c_int), ('status', c_int), ('iscore', c_int), ] XDeviceCoreState = struct_anon_129 # /usr/include/X11/extensions/XInput.h:5546 class struct_anon_130(Structure): __slots__ = [ 'control', 'length', 'enable', ] struct_anon_130._fields_ = [ ('control', XID), ('length', c_int), ('enable', c_int), ] XDeviceEnableControl = struct_anon_130 # /usr/include/X11/extensions/XInput.h:5552 class struct_anon_131(Structure): __slots__ = [ 'control', 'length', 'enable', ] struct_anon_131._fields_ = [ ('control', XID), ('length', c_int), ('enable', c_int), ] XDeviceEnableState = struct_anon_131 # /usr/include/X11/extensions/XInput.h:5552 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:5564 class struct__XAnyClassinfo(Structure): __slots__ = [ 'class', 'length', ] struct__XAnyClassinfo._fields_ = [ ('class', XID), ('length', c_int), ] XAnyClassInfo = struct__XAnyClassinfo # /usr/include/X11/extensions/XInput.h:5573 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:5575 class struct__XDeviceInfo(Structure): __slots__ = [ 'id', 'type', 'name', 'num_classes', 'use', 'inputclassinfo', ] Atom = pyglet.libs.x11.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:5585 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:5587 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:5600 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:5602 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:5612 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:5614 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:5620 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:5622 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:5636 class struct_anon_132(Structure): __slots__ = [ 'input_class', 'event_type_base', ] struct_anon_132._fields_ = [ ('input_class', c_ubyte), ('event_type_base', c_ubyte), ] XInputClassInfo = struct_anon_132 # /usr/include/X11/extensions/XInput.h:5653 class struct_anon_133(Structure): __slots__ = [ 'device_id', 'num_classes', 'classes', ] struct_anon_133._fields_ = [ ('device_id', XID), ('num_classes', c_int), ('classes', POINTER(XInputClassInfo)), ] XDevice = struct_anon_133 # /usr/include/X11/extensions/XInput.h:5659 class struct_anon_134(Structure): __slots__ = [ 'event_type', 'device', ] struct_anon_134._fields_ = [ ('event_type', XEventClass), ('device', XID), ] XEventList = struct_anon_134 # /usr/include/X11/extensions/XInput.h:5672 class struct_anon_135(Structure): __slots__ = [ 'time', 'data', ] struct_anon_135._fields_ = [ ('time', Time), ('data', POINTER(c_int)), ] XDeviceTimeCoord = struct_anon_135 # /usr/include/X11/extensions/XInput.h:5685 class struct_anon_136(Structure): __slots__ = [ 'device_id', 'num_classes', 'data', ] struct_anon_136._fields_ = [ ('device_id', XID), ('num_classes', c_int), ('data', POINTER(XInputClass)), ] XDeviceState = struct_anon_136 # /usr/include/X11/extensions/XInput.h:5699 class struct_anon_137(Structure): __slots__ = [ 'class', 'length', 'num_valuators', 'mode', 'valuators', ] struct_anon_137._fields_ = [ ('class', c_ubyte), ('length', c_ubyte), ('num_valuators', c_ubyte), ('mode', c_ubyte), ('valuators', POINTER(c_int)), ] XValuatorState = struct_anon_137 # /usr/include/X11/extensions/XInput.h:5722 class struct_anon_138(Structure): __slots__ = [ 'class', 'length', 'num_keys', 'keys', ] struct_anon_138._fields_ = [ ('class', c_ubyte), ('length', c_ubyte), ('num_keys', c_short), ('keys', c_char * 32), ] XKeyState = struct_anon_138 # /usr/include/X11/extensions/XInput.h:5733 class struct_anon_139(Structure): __slots__ = [ 'class', 'length', 'num_buttons', 'buttons', ] struct_anon_139._fields_ = [ ('class', c_ubyte), ('length', c_ubyte), ('num_buttons', c_short), ('buttons', c_char * 32), ] XButtonState = struct_anon_139 # /usr/include/X11/extensions/XInput.h:5744 # /usr/include/X11/extensions/XInput.h:5754 XChangeKeyboardDevice = _lib.XChangeKeyboardDevice XChangeKeyboardDevice.restype = c_int XChangeKeyboardDevice.argtypes = [POINTER(Display), POINTER(XDevice)] # /usr/include/X11/extensions/XInput.h:5759 XChangePointerDevice = _lib.XChangePointerDevice XChangePointerDevice.restype = c_int XChangePointerDevice.argtypes = [POINTER(Display), POINTER(XDevice), c_int, c_int] # /usr/include/X11/extensions/XInput.h:5766 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:5778 XUngrabDevice = _lib.XUngrabDevice XUngrabDevice.restype = c_int XUngrabDevice.argtypes = [POINTER(Display), POINTER(XDevice), Time] # /usr/include/X11/extensions/XInput.h:5784 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:5798 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:5807 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:5821 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:5830 XAllowDeviceEvents = _lib.XAllowDeviceEvents XAllowDeviceEvents.restype = c_int XAllowDeviceEvents.argtypes = [POINTER(Display), POINTER(XDevice), c_int, Time] # /usr/include/X11/extensions/XInput.h:5837 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:5845 XSetDeviceFocus = _lib.XSetDeviceFocus XSetDeviceFocus.restype = c_int XSetDeviceFocus.argtypes = [POINTER(Display), POINTER(XDevice), Window, c_int, Time] # /usr/include/X11/extensions/XInput.h:5853 XGetFeedbackControl = _lib.XGetFeedbackControl XGetFeedbackControl.restype = POINTER(XFeedbackState) XGetFeedbackControl.argtypes = [POINTER(Display), POINTER(XDevice), POINTER(c_int)] # /usr/include/X11/extensions/XInput.h:5859 XFreeFeedbackList = _lib.XFreeFeedbackList XFreeFeedbackList.restype = None XFreeFeedbackList.argtypes = [POINTER(XFeedbackState)] # /usr/include/X11/extensions/XInput.h:5863 XChangeFeedbackControl = _lib.XChangeFeedbackControl XChangeFeedbackControl.restype = c_int XChangeFeedbackControl.argtypes = [POINTER(Display), POINTER(XDevice), c_ulong, POINTER(XFeedbackControl)] # /usr/include/X11/extensions/XInput.h:5870 XDeviceBell = _lib.XDeviceBell XDeviceBell.restype = c_int XDeviceBell.argtypes = [POINTER(Display), POINTER(XDevice), XID, XID, c_int] KeyCode = pyglet.libs.x11.xlib.KeyCode # /usr/include/X11/extensions/XInput.h:5878 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:5890 XChangeDeviceKeyMapping = _lib.XChangeDeviceKeyMapping XChangeDeviceKeyMapping.restype = c_int XChangeDeviceKeyMapping.argtypes = [POINTER(Display), POINTER(XDevice), c_int, c_int, POINTER(KeySym), c_int] XModifierKeymap = pyglet.libs.x11.xlib.XModifierKeymap # /usr/include/X11/extensions/XInput.h:5899 XGetDeviceModifierMapping = _lib.XGetDeviceModifierMapping XGetDeviceModifierMapping.restype = POINTER(XModifierKeymap) XGetDeviceModifierMapping.argtypes = [POINTER(Display), POINTER(XDevice)] # /usr/include/X11/extensions/XInput.h:5904 XSetDeviceModifierMapping = _lib.XSetDeviceModifierMapping XSetDeviceModifierMapping.restype = c_int XSetDeviceModifierMapping.argtypes = [POINTER(Display), POINTER(XDevice), POINTER(XModifierKeymap)] # /usr/include/X11/extensions/XInput.h:5910 XSetDeviceButtonMapping = _lib.XSetDeviceButtonMapping XSetDeviceButtonMapping.restype = c_int XSetDeviceButtonMapping.argtypes = [POINTER(Display), POINTER(XDevice), POINTER(c_ubyte), c_int] # /usr/include/X11/extensions/XInput.h:5917 XGetDeviceButtonMapping = _lib.XGetDeviceButtonMapping XGetDeviceButtonMapping.restype = c_int XGetDeviceButtonMapping.argtypes = [POINTER(Display), POINTER(XDevice), POINTER(c_ubyte), c_uint] # /usr/include/X11/extensions/XInput.h:5924 XQueryDeviceState = _lib.XQueryDeviceState XQueryDeviceState.restype = POINTER(XDeviceState) XQueryDeviceState.argtypes = [POINTER(Display), POINTER(XDevice)] # /usr/include/X11/extensions/XInput.h:5929 XFreeDeviceState = _lib.XFreeDeviceState XFreeDeviceState.restype = None XFreeDeviceState.argtypes = [POINTER(XDeviceState)] # /usr/include/X11/extensions/XInput.h:5933 XGetExtensionVersion = _lib.XGetExtensionVersion XGetExtensionVersion.restype = POINTER(XExtensionVersion) XGetExtensionVersion.argtypes = [POINTER(Display), c_char_p] # /usr/include/X11/extensions/XInput.h:5938 XListInputDevices = _lib.XListInputDevices XListInputDevices.restype = POINTER(XDeviceInfo) XListInputDevices.argtypes = [POINTER(Display), POINTER(c_int)] # /usr/include/X11/extensions/XInput.h:5943 XFreeDeviceList = _lib.XFreeDeviceList XFreeDeviceList.restype = None XFreeDeviceList.argtypes = [POINTER(XDeviceInfo)] # /usr/include/X11/extensions/XInput.h:5947 XOpenDevice = _lib.XOpenDevice XOpenDevice.restype = POINTER(XDevice) XOpenDevice.argtypes = [POINTER(Display), XID] # /usr/include/X11/extensions/XInput.h:5952 XCloseDevice = _lib.XCloseDevice XCloseDevice.restype = c_int XCloseDevice.argtypes = [POINTER(Display), POINTER(XDevice)] # /usr/include/X11/extensions/XInput.h:5957 XSetDeviceMode = _lib.XSetDeviceMode XSetDeviceMode.restype = c_int XSetDeviceMode.argtypes = [POINTER(Display), POINTER(XDevice), c_int] # /usr/include/X11/extensions/XInput.h:5963 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:5971 XGetDeviceControl = _lib.XGetDeviceControl XGetDeviceControl.restype = POINTER(XDeviceControl) XGetDeviceControl.argtypes = [POINTER(Display), POINTER(XDevice), c_int] # /usr/include/X11/extensions/XInput.h:5977 XChangeDeviceControl = _lib.XChangeDeviceControl XChangeDeviceControl.restype = c_int XChangeDeviceControl.argtypes = [POINTER(Display), POINTER(XDevice), c_int, POINTER(XDeviceControl)] # /usr/include/X11/extensions/XInput.h:5984 XSelectExtensionEvent = _lib.XSelectExtensionEvent XSelectExtensionEvent.restype = c_int XSelectExtensionEvent.argtypes = [POINTER(Display), Window, POINTER(XEventClass), c_int] # /usr/include/X11/extensions/XInput.h:5991 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:6000 XChangeDeviceDontPropagateList = _lib.XChangeDeviceDontPropagateList XChangeDeviceDontPropagateList.restype = c_int XChangeDeviceDontPropagateList.argtypes = [POINTER(Display), Window, c_int, POINTER(XEventClass), c_int] # /usr/include/X11/extensions/XInput.h:6008 XGetDeviceDontPropagateList = _lib.XGetDeviceDontPropagateList XGetDeviceDontPropagateList.restype = POINTER(XEventClass) XGetDeviceDontPropagateList.argtypes = [POINTER(Display), Window, POINTER(c_int)] XEvent = pyglet.libs.x11.xlib.XEvent # /usr/include/X11/extensions/XInput.h:6014 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:6024 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:6034 XFreeDeviceMotionEvents = _lib.XFreeDeviceMotionEvents XFreeDeviceMotionEvents.restype = None XFreeDeviceMotionEvents.argtypes = [POINTER(XDeviceTimeCoord)] # /usr/include/X11/extensions/XInput.h:6038 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
# objective-ctypes # # Copyright (c) 2011, Phillip Nguyen # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # Neither the name of objective-ctypes nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import sys import platform import struct from ctypes import * from ctypes import util from .cocoatypes import * __LP64__ = (8*struct.calcsize("P") == 64) __i386__ = (platform.machine() == 'i386') if sizeof(c_void_p) == 4: c_ptrdiff_t = c_int32 elif sizeof(c_void_p) == 8: c_ptrdiff_t = c_int64 ###################################################################### objc = cdll.LoadLibrary(util.find_library('objc')) ###################################################################### # BOOL class_addIvar(Class cls, const char *name, size_t size, uint8_t alignment, const char *types) objc.class_addIvar.restype = c_bool objc.class_addIvar.argtypes = [c_void_p, c_char_p, c_size_t, c_uint8, c_char_p] # BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types) objc.class_addMethod.restype = c_bool # BOOL class_addProtocol(Class cls, Protocol *protocol) objc.class_addProtocol.restype = c_bool objc.class_addProtocol.argtypes = [c_void_p, c_void_p] # BOOL class_conformsToProtocol(Class cls, Protocol *protocol) objc.class_conformsToProtocol.restype = c_bool objc.class_conformsToProtocol.argtypes = [c_void_p, c_void_p] # Ivar * class_copyIvarList(Class cls, unsigned int *outCount) # Returns an array of pointers of type Ivar describing instance variables. # The array has *outCount pointers followed by a NULL terminator. # You must free() the returned array. objc.class_copyIvarList.restype = POINTER(c_void_p) objc.class_copyIvarList.argtypes = [c_void_p, POINTER(c_uint)] # Method * class_copyMethodList(Class cls, unsigned int *outCount) # Returns an array of pointers of type Method describing instance methods. # The array has *outCount pointers followed by a NULL terminator. # You must free() the returned array. objc.class_copyMethodList.restype = POINTER(c_void_p) objc.class_copyMethodList.argtypes = [c_void_p, POINTER(c_uint)] # objc_property_t * class_copyPropertyList(Class cls, unsigned int *outCount) # Returns an array of pointers of type objc_property_t describing properties. # The array has *outCount pointers followed by a NULL terminator. # You must free() the returned array. objc.class_copyPropertyList.restype = POINTER(c_void_p) objc.class_copyPropertyList.argtypes = [c_void_p, POINTER(c_uint)] # Protocol ** class_copyProtocolList(Class cls, unsigned int *outCount) # Returns an array of pointers of type Protocol* describing protocols. # The array has *outCount pointers followed by a NULL terminator. # You must free() the returned array. objc.class_copyProtocolList.restype = POINTER(c_void_p) objc.class_copyProtocolList.argtypes = [c_void_p, POINTER(c_uint)] # id class_createInstance(Class cls, size_t extraBytes) objc.class_createInstance.restype = c_void_p objc.class_createInstance.argtypes = [c_void_p, c_size_t] # Method class_getClassMethod(Class aClass, SEL aSelector) # Will also search superclass for implementations. objc.class_getClassMethod.restype = c_void_p objc.class_getClassMethod.argtypes = [c_void_p, c_void_p] # Ivar class_getClassVariable(Class cls, const char* name) objc.class_getClassVariable.restype = c_void_p objc.class_getClassVariable.argtypes = [c_void_p, c_char_p] # Method class_getInstanceMethod(Class aClass, SEL aSelector) # Will also search superclass for implementations. objc.class_getInstanceMethod.restype = c_void_p objc.class_getInstanceMethod.argtypes = [c_void_p, c_void_p] # size_t class_getInstanceSize(Class cls) objc.class_getInstanceSize.restype = c_size_t objc.class_getInstanceSize.argtypes = [c_void_p] # Ivar class_getInstanceVariable(Class cls, const char* name) objc.class_getInstanceVariable.restype = c_void_p objc.class_getInstanceVariable.argtypes = [c_void_p, c_char_p] # const char *class_getIvarLayout(Class cls) objc.class_getIvarLayout.restype = c_char_p objc.class_getIvarLayout.argtypes = [c_void_p] # IMP class_getMethodImplementation(Class cls, SEL name) objc.class_getMethodImplementation.restype = c_void_p objc.class_getMethodImplementation.argtypes = [c_void_p, c_void_p] # IMP class_getMethodImplementation_stret(Class cls, SEL name) objc.class_getMethodImplementation_stret.restype = c_void_p objc.class_getMethodImplementation_stret.argtypes = [c_void_p, c_void_p] # const char * class_getName(Class cls) objc.class_getName.restype = c_char_p objc.class_getName.argtypes = [c_void_p] # objc_property_t class_getProperty(Class cls, const char *name) objc.class_getProperty.restype = c_void_p objc.class_getProperty.argtypes = [c_void_p, c_char_p] # Class class_getSuperclass(Class cls) objc.class_getSuperclass.restype = c_void_p objc.class_getSuperclass.argtypes = [c_void_p] # int class_getVersion(Class theClass) objc.class_getVersion.restype = c_int objc.class_getVersion.argtypes = [c_void_p] # const char *class_getWeakIvarLayout(Class cls) objc.class_getWeakIvarLayout.restype = c_char_p objc.class_getWeakIvarLayout.argtypes = [c_void_p] # BOOL class_isMetaClass(Class cls) objc.class_isMetaClass.restype = c_bool objc.class_isMetaClass.argtypes = [c_void_p] # IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types) objc.class_replaceMethod.restype = c_void_p objc.class_replaceMethod.argtypes = [c_void_p, c_void_p, c_void_p, c_char_p] # BOOL class_respondsToSelector(Class cls, SEL sel) objc.class_respondsToSelector.restype = c_bool objc.class_respondsToSelector.argtypes = [c_void_p, c_void_p] # void class_setIvarLayout(Class cls, const char *layout) objc.class_setIvarLayout.restype = None objc.class_setIvarLayout.argtypes = [c_void_p, c_char_p] # Class class_setSuperclass(Class cls, Class newSuper) objc.class_setSuperclass.restype = c_void_p objc.class_setSuperclass.argtypes = [c_void_p, c_void_p] # void class_setVersion(Class theClass, int version) objc.class_setVersion.restype = None objc.class_setVersion.argtypes = [c_void_p, c_int] # void class_setWeakIvarLayout(Class cls, const char *layout) objc.class_setWeakIvarLayout.restype = None objc.class_setWeakIvarLayout.argtypes = [c_void_p, c_char_p] ###################################################################### # const char * ivar_getName(Ivar ivar) objc.ivar_getName.restype = c_char_p objc.ivar_getName.argtypes = [c_void_p] # ptrdiff_t ivar_getOffset(Ivar ivar) objc.ivar_getOffset.restype = c_ptrdiff_t objc.ivar_getOffset.argtypes = [c_void_p] # const char * ivar_getTypeEncoding(Ivar ivar) objc.ivar_getTypeEncoding.restype = c_char_p objc.ivar_getTypeEncoding.argtypes = [c_void_p] ###################################################################### # char * method_copyArgumentType(Method method, unsigned int index) # You must free() the returned string. objc.method_copyArgumentType.restype = c_char_p objc.method_copyArgumentType.argtypes = [c_void_p, c_uint] # char * method_copyReturnType(Method method) # You must free() the returned string. objc.method_copyReturnType.restype = c_char_p objc.method_copyReturnType.argtypes = [c_void_p] # void method_exchangeImplementations(Method m1, Method m2) objc.method_exchangeImplementations.restype = None objc.method_exchangeImplementations.argtypes = [c_void_p, c_void_p] # void method_getArgumentType(Method method, unsigned int index, char *dst, size_t dst_len) # Functionally similar to strncpy(dst, parameter_type, dst_len). objc.method_getArgumentType.restype = None objc.method_getArgumentType.argtypes = [c_void_p, c_uint, c_char_p, c_size_t] # IMP method_getImplementation(Method method) objc.method_getImplementation.restype = c_void_p objc.method_getImplementation.argtypes = [c_void_p] # SEL method_getName(Method method) objc.method_getName.restype = c_void_p objc.method_getName.argtypes = [c_void_p] # unsigned method_getNumberOfArguments(Method method) objc.method_getNumberOfArguments.restype = c_uint objc.method_getNumberOfArguments.argtypes = [c_void_p] # void method_getReturnType(Method method, char *dst, size_t dst_len) # Functionally similar to strncpy(dst, return_type, dst_len) objc.method_getReturnType.restype = None objc.method_getReturnType.argtypes = [c_void_p, c_char_p, c_size_t] # const char * method_getTypeEncoding(Method method) objc.method_getTypeEncoding.restype = c_char_p objc.method_getTypeEncoding.argtypes = [c_void_p] # IMP method_setImplementation(Method method, IMP imp) objc.method_setImplementation.restype = c_void_p objc.method_setImplementation.argtypes = [c_void_p, c_void_p] ###################################################################### # Class objc_allocateClassPair(Class superclass, const char *name, size_t extraBytes) objc.objc_allocateClassPair.restype = c_void_p objc.objc_allocateClassPair.argtypes = [c_void_p, c_char_p, c_size_t] # Protocol **objc_copyProtocolList(unsigned int *outCount) # Returns an array of *outcount pointers followed by NULL terminator. # You must free() the array. objc.objc_copyProtocolList.restype = POINTER(c_void_p) objc.objc_copyProtocolList.argtypes = [POINTER(c_int)] # id objc_getAssociatedObject(id object, void *key) objc.objc_getAssociatedObject.restype = c_void_p objc.objc_getAssociatedObject.argtypes = [c_void_p, c_void_p] # id objc_getClass(const char *name) objc.objc_getClass.restype = c_void_p objc.objc_getClass.argtypes = [c_char_p] # int objc_getClassList(Class *buffer, int bufferLen) # Pass None for buffer to obtain just the total number of classes. objc.objc_getClassList.restype = c_int objc.objc_getClassList.argtypes = [c_void_p, c_int] # id objc_getMetaClass(const char *name) objc.objc_getMetaClass.restype = c_void_p objc.objc_getMetaClass.argtypes = [c_char_p] # Protocol *objc_getProtocol(const char *name) objc.objc_getProtocol.restype = c_void_p objc.objc_getProtocol.argtypes = [c_char_p] # You should set return and argument types depending on context. # id objc_msgSend(id theReceiver, SEL theSelector, ...) # id objc_msgSendSuper(struct objc_super *super, SEL op, ...) # void objc_msgSendSuper_stret(struct objc_super *super, SEL op, ...) objc.objc_msgSendSuper_stret.restype = None # double objc_msgSend_fpret(id self, SEL op, ...) # objc.objc_msgSend_fpret.restype = c_double # void objc_msgSend_stret(void * stretAddr, id theReceiver, SEL theSelector, ...) objc.objc_msgSend_stret.restype = None # void objc_registerClassPair(Class cls) objc.objc_registerClassPair.restype = None objc.objc_registerClassPair.argtypes = [c_void_p] # void objc_removeAssociatedObjects(id object) objc.objc_removeAssociatedObjects.restype = None objc.objc_removeAssociatedObjects.argtypes = [c_void_p] # void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy) objc.objc_setAssociatedObject.restype = None objc.objc_setAssociatedObject.argtypes = [c_void_p, c_void_p, c_void_p, c_int] ###################################################################### # id object_copy(id obj, size_t size) objc.object_copy.restype = c_void_p objc.object_copy.argtypes = [c_void_p, c_size_t] # id object_dispose(id obj) objc.object_dispose.restype = c_void_p objc.object_dispose.argtypes = [c_void_p] # Class object_getClass(id object) objc.object_getClass.restype = c_void_p objc.object_getClass.argtypes = [c_void_p] # const char *object_getClassName(id obj) objc.object_getClassName.restype = c_char_p objc.object_getClassName.argtypes = [c_void_p] # Ivar object_getInstanceVariable(id obj, const char *name, void **outValue) objc.object_getInstanceVariable.restype = c_void_p objc.object_getInstanceVariable.argtypes=[c_void_p, c_char_p, c_void_p] # id object_getIvar(id object, Ivar ivar) objc.object_getIvar.restype = c_void_p objc.object_getIvar.argtypes = [c_void_p, c_void_p] # Class object_setClass(id object, Class cls) objc.object_setClass.restype = c_void_p objc.object_setClass.argtypes = [c_void_p, c_void_p] # Ivar object_setInstanceVariable(id obj, const char *name, void *value) # Set argtypes based on the data type of the instance variable. objc.object_setInstanceVariable.restype = c_void_p # void object_setIvar(id object, Ivar ivar, id value) objc.object_setIvar.restype = None objc.object_setIvar.argtypes = [c_void_p, c_void_p, c_void_p] ###################################################################### # const char *property_getAttributes(objc_property_t property) objc.property_getAttributes.restype = c_char_p objc.property_getAttributes.argtypes = [c_void_p] # const char *property_getName(objc_property_t property) objc.property_getName.restype = c_char_p objc.property_getName.argtypes = [c_void_p] ###################################################################### # BOOL protocol_conformsToProtocol(Protocol *proto, Protocol *other) objc.protocol_conformsToProtocol.restype = c_bool objc.protocol_conformsToProtocol.argtypes = [c_void_p, c_void_p] class OBJC_METHOD_DESCRIPTION(Structure): _fields_ = [ ("name", c_void_p), ("types", c_char_p) ] # struct objc_method_description *protocol_copyMethodDescriptionList(Protocol *p, BOOL isRequiredMethod, BOOL isInstanceMethod, unsigned int *outCount) # You must free() the returned array. objc.protocol_copyMethodDescriptionList.restype = POINTER(OBJC_METHOD_DESCRIPTION) objc.protocol_copyMethodDescriptionList.argtypes = [c_void_p, c_bool, c_bool, POINTER(c_uint)] # objc_property_t * protocol_copyPropertyList(Protocol *protocol, unsigned int *outCount) objc.protocol_copyPropertyList.restype = c_void_p objc.protocol_copyPropertyList.argtypes = [c_void_p, POINTER(c_uint)] # Protocol **protocol_copyProtocolList(Protocol *proto, unsigned int *outCount) objc.protocol_copyProtocolList = POINTER(c_void_p) objc.protocol_copyProtocolList.argtypes = [c_void_p, POINTER(c_uint)] # struct objc_method_description protocol_getMethodDescription(Protocol *p, SEL aSel, BOOL isRequiredMethod, BOOL isInstanceMethod) objc.protocol_getMethodDescription.restype = OBJC_METHOD_DESCRIPTION objc.protocol_getMethodDescription.argtypes = [c_void_p, c_void_p, c_bool, c_bool] # const char *protocol_getName(Protocol *p) objc.protocol_getName.restype = c_char_p objc.protocol_getName.argtypes = [c_void_p] ###################################################################### # const char* sel_getName(SEL aSelector) objc.sel_getName.restype = c_char_p objc.sel_getName.argtypes = [c_void_p] # SEL sel_getUid(const char *str) # Use sel_registerName instead. # BOOL sel_isEqual(SEL lhs, SEL rhs) objc.sel_isEqual.restype = c_bool objc.sel_isEqual.argtypes = [c_void_p, c_void_p] # SEL sel_registerName(const char *str) objc.sel_registerName.restype = c_void_p objc.sel_registerName.argtypes = [c_char_p] ###################################################################### def ensure_bytes(x): if isinstance(x, bytes): return x return x.encode('ascii') ###################################################################### def get_selector(name): return c_void_p(objc.sel_registerName(ensure_bytes(name))) def get_class(name): return c_void_p(objc.objc_getClass(ensure_bytes(name))) def get_object_class(obj): return c_void_p(objc.object_getClass(obj)) def get_metaclass(name): return c_void_p(objc.objc_getMetaClass(ensure_bytes(name))) def get_superclass_of_object(obj): cls = c_void_p(objc.object_getClass(obj)) return c_void_p(objc.class_getSuperclass(cls)) # http://www.sealiesoftware.com/blog/archive/2008/10/30/objc_explain_objc_msgSend_stret.html # http://www.x86-64.org/documentation/abi-0.99.pdf (pp.17-23) # executive summary: on x86-64, who knows? def x86_should_use_stret(restype): """Try to figure out when a return type will be passed on stack.""" if type(restype) != type(Structure): return False if not __LP64__ and sizeof(restype) <= 8: return False if __LP64__ and sizeof(restype) <= 16: # maybe? I don't know? return False return True # http://www.sealiesoftware.com/blog/archive/2008/11/16/objc_explain_objc_msgSend_fpret.html def should_use_fpret(restype): """Determine if objc_msgSend_fpret is required to return a floating point type.""" if not __i386__: # Unneeded on non-intel processors return False if __LP64__ and restype == c_longdouble: # Use only for long double on x86_64 return True if not __LP64__ and restype in (c_float, c_double, c_longdouble): return True return False # By default, assumes that restype is c_void_p # and that all arguments are wrapped inside c_void_p. # Use the restype and argtypes keyword arguments to # change these values. restype should be a ctypes type # and argtypes should be a list of ctypes types for # the arguments of the message only. def send_message(receiver, selName, *args, **kwargs): if isinstance(receiver, str): receiver = get_class(receiver) selector = get_selector(selName) restype = kwargs.get('restype', c_void_p) #print 'send_message', receiver, selName, args, kwargs argtypes = kwargs.get('argtypes', []) # Choose the correct version of objc_msgSend based on return type. if should_use_fpret(restype): objc.objc_msgSend_fpret.restype = restype objc.objc_msgSend_fpret.argtypes = [c_void_p, c_void_p] + argtypes result = objc.objc_msgSend_fpret(receiver, selector, *args) elif x86_should_use_stret(restype): objc.objc_msgSend_stret.argtypes = [POINTER(restype), c_void_p, c_void_p] + argtypes result = restype() objc.objc_msgSend_stret(byref(result), receiver, selector, *args) else: objc.objc_msgSend.restype = restype objc.objc_msgSend.argtypes = [c_void_p, c_void_p] + argtypes result = objc.objc_msgSend(receiver, selector, *args) if restype == c_void_p: result = c_void_p(result) return result class OBJC_SUPER(Structure): _fields_ = [ ('receiver', c_void_p), ('class', c_void_p) ] OBJC_SUPER_PTR = POINTER(OBJC_SUPER) #http://stackoverflow.com/questions/3095360/what-exactly-is-super-in-objective-c def send_super(receiver, selName, *args, **kwargs): #print 'send_super', receiver, selName, args if hasattr(receiver, '_as_parameter_'): receiver = receiver._as_parameter_ superclass = get_superclass_of_object(receiver) super_struct = OBJC_SUPER(receiver, superclass) selector = get_selector(selName) restype = kwargs.get('restype', c_void_p) argtypes = kwargs.get('argtypes', None) objc.objc_msgSendSuper.restype = restype if argtypes: objc.objc_msgSendSuper.argtypes = [OBJC_SUPER_PTR, c_void_p] + argtypes else: objc.objc_msgSendSuper.argtypes = None result = objc.objc_msgSendSuper(byref(super_struct), selector, *args) if restype == c_void_p: result = c_void_p(result) return result ###################################################################### cfunctype_table = {} def parse_type_encoding(encoding): """Takes a type encoding string and outputs a list of the separated type codes. Currently does not handle unions or bitfields and strips out any field width specifiers or type specifiers from the encoding. For Python 3.2+, encoding is assumed to be a bytes object and not unicode. Examples: parse_type_encoding('^v16@0:8') --> ['^v', '@', ':'] parse_type_encoding('{CGSize=dd}40@0:8{CGSize=dd}16Q32') --> ['{CGSize=dd}', '@', ':', '{CGSize=dd}', 'Q'] """ type_encodings = [] brace_count = 0 # number of unclosed curly braces bracket_count = 0 # number of unclosed square brackets typecode = b'' for c in encoding: # In Python 3, c comes out as an integer in the range 0-255. In Python 2, c is a single character string. # To fix the disparity, we convert c to a bytes object if necessary. if isinstance(c, int): c = bytes([c]) if c == b'{': # Check if this marked the end of previous type code. if typecode and typecode[-1:] != b'^' and brace_count == 0 and bracket_count == 0: type_encodings.append(typecode) typecode = b'' typecode += c brace_count += 1 elif c == b'}': typecode += c brace_count -= 1 assert(brace_count >= 0) elif c == b'[': # Check if this marked the end of previous type code. if typecode and typecode[-1:] != b'^' and brace_count == 0 and bracket_count == 0: type_encodings.append(typecode) typecode = b'' typecode += c bracket_count += 1 elif c == b']': typecode += c bracket_count -= 1 assert(bracket_count >= 0) elif brace_count or bracket_count: # Anything encountered while inside braces or brackets gets stuck on. typecode += c elif c in b'0123456789': # Ignore field width specifiers for now. pass elif c in b'rnNoORV': # Also ignore type specifiers. pass elif c in b'^cislqCISLQfdBv*@#:b?': if typecode and typecode[-1:] == b'^': # Previous char was pointer specifier, so keep going. typecode += c else: # Add previous type code to the list. if typecode: type_encodings.append(typecode) # Start a new type code. typecode = c # Add the last type code to the list if typecode: type_encodings.append(typecode) return type_encodings # Limited to basic types and pointers to basic types. # Does not try to handle arrays, arbitrary structs, unions, or bitfields. # Assume that encoding is a bytes object and not unicode. def cfunctype_for_encoding(encoding): # Check if we've already created a CFUNCTYPE for this encoding. # If so, then return the cached CFUNCTYPE. if encoding in cfunctype_table: return cfunctype_table[encoding] # Otherwise, create a new CFUNCTYPE for the encoding. typecodes = {b'c':c_char, b'i':c_int, b's':c_short, b'l':c_long, b'q':c_longlong, b'C':c_ubyte, b'I':c_uint, b'S':c_ushort, b'L':c_ulong, b'Q':c_ulonglong, b'f':c_float, b'd':c_double, b'B':c_bool, b'v':None, b'*':c_char_p, b'@':c_void_p, b'#':c_void_p, b':':c_void_p, NSPointEncoding:NSPoint, NSSizeEncoding:NSSize, NSRectEncoding:NSRect, NSRangeEncoding:NSRange, PyObjectEncoding:py_object} argtypes = [] for code in parse_type_encoding(encoding): if code in typecodes: argtypes.append(typecodes[code]) elif code[0:1] == b'^' and code[1:] in typecodes: argtypes.append(POINTER(typecodes[code[1:]])) else: raise Exception('unknown type encoding: ' + code) cfunctype = CFUNCTYPE(*argtypes) # Cache the new CFUNCTYPE in the cfunctype_table. # We do this mainly because it prevents the CFUNCTYPE # from being garbage-collected while we need it. cfunctype_table[encoding] = cfunctype return cfunctype ###################################################################### # After calling create_subclass, you must first register # it with register_subclass before you may use it. # You can add new methods after the class is registered, # but you cannot add any new ivars. def create_subclass(superclass, name): if isinstance(superclass, str): superclass = get_class(superclass) return c_void_p(objc.objc_allocateClassPair(superclass, ensure_bytes(name), 0)) def register_subclass(subclass): objc.objc_registerClassPair(subclass) # types is a string encoding the argument types of the method. # The first type code of types is the return type (e.g. 'v' if void) # The second type code must be '@' for id self. # The third type code must be ':' for SEL cmd. # Additional type codes are for types of other arguments if any. def add_method(cls, selName, method, types): type_encodings = parse_type_encoding(types) assert(type_encodings[1] == b'@') # ensure id self typecode assert(type_encodings[2] == b':') # ensure SEL cmd typecode selector = get_selector(selName) cfunctype = cfunctype_for_encoding(types) imp = cfunctype(method) objc.class_addMethod.argtypes = [c_void_p, c_void_p, cfunctype, c_char_p] objc.class_addMethod(cls, selector, imp, types) return imp def add_ivar(cls, name, vartype): return objc.class_addIvar(cls, ensure_bytes(name), sizeof(vartype), alignment(vartype), encoding_for_ctype(vartype)) def set_instance_variable(obj, varname, value, vartype): objc.object_setInstanceVariable.argtypes = [c_void_p, c_char_p, vartype] objc.object_setInstanceVariable(obj, ensure_bytes(varname), value) def get_instance_variable(obj, varname, vartype): variable = vartype() objc.object_getInstanceVariable(obj, ensure_bytes(varname), byref(variable)) return variable.value ###################################################################### class ObjCMethod(object): """This represents an unbound Objective-C method (really an IMP).""" # Note, need to map 'c' to c_byte rather than c_char, because otherwise # ctypes converts the value into a one-character string which is generally # not what we want at all, especially when the 'c' represents a bool var. typecodes = {b'c':c_byte, b'i':c_int, b's':c_short, b'l':c_long, b'q':c_longlong, b'C':c_ubyte, b'I':c_uint, b'S':c_ushort, b'L':c_ulong, b'Q':c_ulonglong, b'f':c_float, b'd':c_double, b'B':c_bool, b'v':None, b'Vv':None, b'*':c_char_p, b'@':c_void_p, b'#':c_void_p, b':':c_void_p, b'^v':c_void_p, b'?':c_void_p, NSPointEncoding:NSPoint, NSSizeEncoding:NSSize, NSRectEncoding:NSRect, NSRangeEncoding:NSRange, PyObjectEncoding:py_object} cfunctype_table = {} def __init__(self, method): """Initialize with an Objective-C Method pointer. We then determine the return type and argument type information of the method.""" self.selector = c_void_p(objc.method_getName(method)) self.name = objc.sel_getName(self.selector) self.pyname = self.name.replace(b':', b'_') self.encoding = objc.method_getTypeEncoding(method) self.return_type = objc.method_copyReturnType(method) self.nargs = objc.method_getNumberOfArguments(method) self.imp = c_void_p(objc.method_getImplementation(method)) self.argument_types = [] for i in range(self.nargs): buffer = c_buffer(512) objc.method_getArgumentType(method, i, buffer, len(buffer)) self.argument_types.append(buffer.value) # Get types for all the arguments. try: self.argtypes = [self.ctype_for_encoding(t) for t in self.argument_types] except: #print 'no argtypes encoding for %s (%s)' % (self.name, self.argument_types) self.argtypes = None # Get types for the return type. try: if self.return_type == b'@': self.restype = ObjCInstance elif self.return_type == b'#': self.restype = ObjCClass else: self.restype = self.ctype_for_encoding(self.return_type) except: #print 'no restype encoding for %s (%s)' % (self.name, self.return_type) self.restype = None self.func = None def ctype_for_encoding(self, encoding): """Return ctypes type for an encoded Objective-C type.""" if encoding in self.typecodes: return self.typecodes[encoding] elif encoding[0:1] == b'^' and encoding[1:] in self.typecodes: return POINTER(self.typecodes[encoding[1:]]) elif encoding[0:1] == b'^' and encoding[1:] in [CGImageEncoding, NSZoneEncoding]: # special cases return c_void_p elif encoding[0:1] == b'r' and encoding[1:] in self.typecodes: # const decorator, don't care return self.typecodes[encoding[1:]] elif encoding[0:2] == b'r^' and encoding[2:] in self.typecodes: # const pointer, also don't care return POINTER(self.typecodes[encoding[2:]]) else: raise Exception('unknown encoding for %s: %s' % (self.name, encoding)) def get_prototype(self): """Returns a ctypes CFUNCTYPE for the method.""" if self.restype == ObjCInstance or self.restype == ObjCClass: # Some hacky stuff to get around ctypes issues on 64-bit. Can't let # ctypes convert the return value itself, because it truncates the pointer # along the way. So instead, we must do set the return type to c_void_p to # ensure we get 64-bit addresses and then convert the return value manually. self.prototype = CFUNCTYPE(c_void_p, *self.argtypes) else: self.prototype = CFUNCTYPE(self.restype, *self.argtypes) return self.prototype def __repr__(self): return "<ObjCMethod: %s %s>" % (self.name, self.encoding) def get_callable(self): """Returns a python-callable version of the method's IMP.""" if not self.func: prototype = self.get_prototype() self.func = cast(self.imp, prototype) if self.restype == ObjCInstance or self.restype == ObjCClass: self.func.restype = c_void_p else: self.func.restype = self.restype self.func.argtypes = self.argtypes return self.func def __call__(self, objc_id, *args): """Call the method with the given id and arguments. You do not need to pass in the selector as an argument since it will be automatically provided.""" f = self.get_callable() try: result = f(objc_id, self.selector, *args) # Convert result to python type if it is a instance or class pointer. if self.restype == ObjCInstance: result = ObjCInstance(result) elif self.restype == ObjCClass: result = ObjCClass(result) return result except ArgumentError as error: # Add more useful info to argument error exceptions, then reraise. error.args += ('selector = ' + self.name, 'argtypes =' + str(self.argtypes), 'encoding = ' + self.encoding) raise ###################################################################### class ObjCBoundMethod(object): """This represents an Objective-C method (an IMP) which has been bound to some id which will be passed as the first parameter to the method.""" def __init__(self, method, objc_id): """Initialize with a method and ObjCInstance or ObjCClass object.""" self.method = method self.objc_id = objc_id def __repr__(self): return '<ObjCBoundMethod %s (%s)>' % (self.method.name, self.objc_id) def __call__(self, *args): """Call the method with the given arguments.""" return self.method(self.objc_id, *args) ###################################################################### class ObjCClass(object): """Python wrapper for an Objective-C class.""" # We only create one Python object for each Objective-C class. # Any future calls with the same class will return the previously # created Python object. Note that these aren't weak references. # After you create an ObjCClass, it will exist until the end of the # program. _registered_classes = {} def __new__(cls, class_name_or_ptr): """Create a new ObjCClass instance or return a previously created instance for the given Objective-C class. The argument may be either the name of the class to retrieve, or a pointer to the class.""" # Determine name and ptr values from passed in argument. if isinstance(class_name_or_ptr, str): name = class_name_or_ptr ptr = get_class(name) else: ptr = class_name_or_ptr # Make sure that ptr value is wrapped in c_void_p object # for safety when passing as ctypes argument. if not isinstance(ptr, c_void_p): ptr = c_void_p(ptr) name = objc.class_getName(ptr) # Check if we've already created a Python object for this class # and if so, return it rather than making a new one. if name in cls._registered_classes: return cls._registered_classes[name] # Otherwise create a new Python object and then initialize it. objc_class = super(ObjCClass, cls).__new__(cls) objc_class.ptr = ptr objc_class.name = name objc_class.instance_methods = {} # mapping of name -> instance method objc_class.class_methods = {} # mapping of name -> class method objc_class._as_parameter_ = ptr # for ctypes argument passing # Store the new class in dictionary of registered classes. cls._registered_classes[name] = objc_class # Not sure this is necessary... objc_class.cache_instance_methods() objc_class.cache_class_methods() return objc_class def __repr__(self): return "<ObjCClass: %s at %s>" % (self.name, str(self.ptr.value)) def cache_instance_methods(self): """Create and store python representations of all instance methods implemented by this class (but does not find methods of superclass).""" count = c_uint() method_array = objc.class_copyMethodList(self.ptr, byref(count)) for i in range(count.value): method = c_void_p(method_array[i]) objc_method = ObjCMethod(method) self.instance_methods[objc_method.pyname] = objc_method def cache_class_methods(self): """Create and store python representations of all class methods implemented by this class (but does not find methods of superclass).""" count = c_uint() method_array = objc.class_copyMethodList(objc.object_getClass(self.ptr), byref(count)) for i in range(count.value): method = c_void_p(method_array[i]) objc_method = ObjCMethod(method) self.class_methods[objc_method.pyname] = objc_method def get_instance_method(self, name): """Returns a python representation of the named instance method, either by looking it up in the cached list of methods or by searching for and creating a new method object.""" if name in self.instance_methods: return self.instance_methods[name] else: # If method name isn't in the cached list, it might be a method of # the superclass, so call class_getInstanceMethod to check. selector = get_selector(name.replace(b'_', b':')) method = c_void_p(objc.class_getInstanceMethod(self.ptr, selector)) if method.value: objc_method = ObjCMethod(method) self.instance_methods[name] = objc_method return objc_method return None def get_class_method(self, name): """Returns a python representation of the named class method, either by looking it up in the cached list of methods or by searching for and creating a new method object.""" if name in self.class_methods: return self.class_methods[name] else: # If method name isn't in the cached list, it might be a method of # the superclass, so call class_getInstanceMethod to check. selector = get_selector(name.replace(b'_', b':')) method = c_void_p(objc.class_getClassMethod(self.ptr, selector)) if method.value: objc_method = ObjCMethod(method) self.class_methods[name] = objc_method return objc_method return None def __getattr__(self, name): """Returns a callable method object with the given name.""" # If name refers to a class method, then return a callable object # for the class method with self.ptr as hidden first parameter. name = ensure_bytes(name) method = self.get_class_method(name) if method: return ObjCBoundMethod(method, self.ptr) # If name refers to an instance method, then simply return the method. # The caller will need to supply an instance as the first parameter. method = self.get_instance_method(name) if method: return method # Otherwise, raise an exception. raise AttributeError('ObjCClass %s has no attribute %s' % (self.name, name)) ###################################################################### class ObjCInstance(object): """Python wrapper for an Objective-C instance.""" _cached_objects = {} def __new__(cls, object_ptr): """Create a new ObjCInstance or return a previously created one for the given object_ptr which should be an Objective-C id.""" # Make sure that object_ptr is wrapped in a c_void_p. if not isinstance(object_ptr, c_void_p): object_ptr = c_void_p(object_ptr) # If given a nil pointer, return None. if not object_ptr.value: return None # Check if we've already created an python ObjCInstance for this # object_ptr id and if so, then return it. A single ObjCInstance will # be created for any object pointer when it is first encountered. # This same ObjCInstance will then persist until the object is # deallocated. if object_ptr.value in cls._cached_objects: return cls._cached_objects[object_ptr.value] # Otherwise, create a new ObjCInstance. objc_instance = super(ObjCInstance, cls).__new__(cls) objc_instance.ptr = object_ptr objc_instance._as_parameter_ = object_ptr # Determine class of this object. class_ptr = c_void_p(objc.object_getClass(object_ptr)) objc_instance.objc_class = ObjCClass(class_ptr) # Store new object in the dictionary of cached objects, keyed # by the (integer) memory address pointed to by the object_ptr. cls._cached_objects[object_ptr.value] = objc_instance # Create a DeallocationObserver and associate it with this object. # When the Objective-C object is deallocated, the observer will remove # the ObjCInstance corresponding to the object from the cached objects # dictionary, effectively destroying the ObjCInstance. observer = send_message(send_message('DeallocationObserver', 'alloc'), 'initWithObject:', objc_instance) objc.objc_setAssociatedObject(objc_instance, observer, observer, 0x301) # The observer is retained by the object we associate it to. We release # the observer now so that it will be deallocated when the associated # object is deallocated. send_message(observer, 'release') return objc_instance def __repr__(self): if self.objc_class.name == b'NSCFString': # Display contents of NSString objects from .cocoalibs import cfstring_to_string string = cfstring_to_string(self) return "<ObjCInstance %#x: %s (%s) at %s>" % (id(self), self.objc_class.name, string, str(self.ptr.value)) return "<ObjCInstance %#x: %s at %s>" % (id(self), self.objc_class.name, str(self.ptr.value)) def __getattr__(self, name): """Returns a callable method object with the given name.""" # Search for named instance method in the class object and if it # exists, return callable object with self as hidden argument. # Note: you should give self and not self.ptr as a parameter to # ObjCBoundMethod, so that it will be able to keep the ObjCInstance # alive for chained calls like MyClass.alloc().init() where the # object created by alloc() is not assigned to a variable. name = ensure_bytes(name) method = self.objc_class.get_instance_method(name) if method: return ObjCBoundMethod(method, self) # Else, search for class method with given name in the class object. # If it exists, return callable object with a pointer to the class # as a hidden argument. method = self.objc_class.get_class_method(name) if method: return ObjCBoundMethod(method, self.objc_class.ptr) # Otherwise raise an exception. raise AttributeError('ObjCInstance %s has no attribute %s' % (self.objc_class.name, name)) ###################################################################### def convert_method_arguments(encoding, args): """Used by ObjCSubclass to convert Objective-C method arguments to Python values before passing them on to the Python-defined method.""" new_args = [] arg_encodings = parse_type_encoding(encoding)[3:] for e, a in zip(arg_encodings, args): if e == b'@': new_args.append(ObjCInstance(a)) elif e == b'#': new_args.append(ObjCClass(a)) else: new_args.append(a) return new_args # ObjCSubclass is used to define an Objective-C subclass of an existing # class registered with the runtime. When you create an instance of # ObjCSubclass, it registers the new subclass with the Objective-C # runtime and creates a set of function decorators that you can use to # add instance methods or class methods to the subclass. # # Typical usage would be to first create and register the subclass: # # MySubclass = ObjCSubclass('NSObject', 'MySubclassName') # # then add methods with: # # @MySubclass.method('v') # def methodThatReturnsVoid(self): # pass # # @MySubclass.method('Bi') # def boolReturningMethodWithInt_(self, x): # return True # # @MySubclass.classmethod('@') # def classMethodThatReturnsId(self): # return self # # It is probably a good idea to organize the code related to a single # subclass by either putting it in its own module (note that you don't # actually need to expose any of the method names or the ObjCSubclass) # or by bundling it all up inside a python class definition, perhaps # called MySubclassImplementation. # # It is also possible to add Objective-C ivars to the subclass, however # if you do so, you must call the __init__ method with register=False, # and then call the register method after the ivars have been added. # But rather than creating the ivars in Objective-C land, it is easier # to just define python-based instance variables in your subclass's init # method. # # This class is used only to *define* the interface and implementation # of an Objective-C subclass from python. It should not be used in # any other way. If you want a python representation of the resulting # class, create it with ObjCClass. # # Instances are created as a pointer to the objc object by using: # # myinstance = send_message('MySubclassName', 'alloc') # myinstance = send_message(myinstance, 'init') # # or wrapped inside an ObjCInstance object by using: # # myclass = ObjCClass('MySubclassName') # myinstance = myclass.alloc().init() # class ObjCSubclass(object): """Use this to create a subclass of an existing Objective-C class. It consists primarily of function decorators which you use to add methods to the subclass.""" def __init__(self, superclass, name, register=True): self._imp_table = {} self.name = name self.objc_cls = create_subclass(superclass, name) self._as_parameter_ = self.objc_cls if register: self.register() def register(self): """Register the new class with the Objective-C runtime.""" objc.objc_registerClassPair(self.objc_cls) # We can get the metaclass only after the class is registered. self.objc_metaclass = get_metaclass(self.name) def add_ivar(self, varname, vartype): """Add instance variable named varname to the subclass. varname should be a string. vartype is a ctypes type. The class must be registered AFTER adding instance variables.""" return add_ivar(self.objc_cls, varname, vartype) def add_method(self, method, name, encoding): imp = add_method(self.objc_cls, name, method, encoding) self._imp_table[name] = imp # http://iphonedevelopment.blogspot.com/2008/08/dynamically-adding-class-objects.html def add_class_method(self, method, name, encoding): imp = add_method(self.objc_metaclass, name, method, encoding) self._imp_table[name] = imp def rawmethod(self, encoding): """Decorator for instance methods without any fancy shenanigans. The function must have the signature f(self, cmd, *args) where both self and cmd are just pointers to objc objects.""" # Add encodings for hidden self and cmd arguments. encoding = ensure_bytes(encoding) typecodes = parse_type_encoding(encoding) typecodes.insert(1, b'@:') encoding = b''.join(typecodes) def decorator(f): name = f.__name__.replace('_', ':') self.add_method(f, name, encoding) return f return decorator def method(self, encoding): """Function decorator for instance methods.""" # Add encodings for hidden self and cmd arguments. encoding = ensure_bytes(encoding) typecodes = parse_type_encoding(encoding) typecodes.insert(1, b'@:') encoding = b''.join(typecodes) def decorator(f): def objc_method(objc_self, objc_cmd, *args): py_self = ObjCInstance(objc_self) py_self.objc_cmd = objc_cmd args = convert_method_arguments(encoding, args) result = f(py_self, *args) if isinstance(result, ObjCClass): result = result.ptr.value elif isinstance(result, ObjCInstance): result = result.ptr.value return result name = f.__name__.replace('_', ':') self.add_method(objc_method, name, encoding) return objc_method return decorator def classmethod(self, encoding): """Function decorator for class methods.""" # Add encodings for hidden self and cmd arguments. encoding = ensure_bytes(encoding) typecodes = parse_type_encoding(encoding) typecodes.insert(1, b'@:') encoding = b''.join(typecodes) def decorator(f): def objc_class_method(objc_cls, objc_cmd, *args): py_cls = ObjCClass(objc_cls) py_cls.objc_cmd = objc_cmd args = convert_method_arguments(encoding, args) result = f(py_cls, *args) if isinstance(result, ObjCClass): result = result.ptr.value elif isinstance(result, ObjCInstance): result = result.ptr.value return result name = f.__name__.replace('_', ':') self.add_class_method(objc_class_method, name, encoding) return objc_class_method return decorator ###################################################################### # Instances of DeallocationObserver are associated with every # Objective-C object that gets wrapped inside an ObjCInstance. # Their sole purpose is to watch for when the Objective-C object # is deallocated, and then remove the object from the dictionary # of cached ObjCInstance objects kept by the ObjCInstance class. # # The methods of the class defined below are decorated with # rawmethod() instead of method() because DeallocationObservers # are created inside of ObjCInstance's __new__ method and we have # to be careful to not create another ObjCInstance here (which # happens when the usual method decorator turns the self argument # into an ObjCInstance), or else get trapped in an infinite recursion. class DeallocationObserver_Implementation(object): DeallocationObserver = ObjCSubclass('NSObject', 'DeallocationObserver', register=False) DeallocationObserver.add_ivar('observed_object', c_void_p) DeallocationObserver.register() @DeallocationObserver.rawmethod('@@') def initWithObject_(self, cmd, anObject): self = send_super(self, 'init') self = self.value set_instance_variable(self, 'observed_object', anObject, c_void_p) return self @DeallocationObserver.rawmethod('v') def dealloc(self, cmd): anObject = get_instance_variable(self, 'observed_object', c_void_p) ObjCInstance._cached_objects.pop(anObject, None) send_super(self, 'dealloc') @DeallocationObserver.rawmethod('v') def finalize(self, cmd): # Called instead of dealloc if using garbage collection. # (which would have to be explicitly started with # objc_startCollectorThread(), so probably not too much reason # to have this here, but I guess it can't hurt.) anObject = get_instance_variable(self, 'observed_object', c_void_p) ObjCInstance._cached_objects.pop(anObject, None) send_super(self, 'finalize')
Python
from ctypes import * import sys, platform, struct __LP64__ = (8*struct.calcsize("P") == 64) __i386__ = (platform.machine() == 'i386') PyObjectEncoding = b'{PyObject=@}' def encoding_for_ctype(vartype): typecodes = {c_char:b'c', c_int:b'i', c_short:b's', c_long:b'l', c_longlong:b'q', c_ubyte:b'C', c_uint:b'I', c_ushort:b'S', c_ulong:b'L', c_ulonglong:b'Q', c_float:b'f', c_double:b'd', c_bool:b'B', c_char_p:b'*', c_void_p:b'@', py_object:PyObjectEncoding} return typecodes.get(vartype, b'?') # Note CGBase.h located at # /System/Library/Frameworks/ApplicationServices.framework/Frameworks/CoreGraphics.framework/Headers/CGBase.h # defines CGFloat as double if __LP64__, otherwise it's a float. if __LP64__: NSInteger = c_long NSUInteger = c_ulong CGFloat = c_double NSPointEncoding = b'{CGPoint=dd}' NSSizeEncoding = b'{CGSize=dd}' NSRectEncoding = b'{CGRect={CGPoint=dd}{CGSize=dd}}' NSRangeEncoding = b'{_NSRange=QQ}' else: NSInteger = c_int NSUInteger = c_uint CGFloat = c_float NSPointEncoding = b'{_NSPoint=ff}' NSSizeEncoding = b'{_NSSize=ff}' NSRectEncoding = b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}' NSRangeEncoding = b'{_NSRange=II}' NSIntegerEncoding = encoding_for_ctype(NSInteger) NSUIntegerEncoding = encoding_for_ctype(NSUInteger) CGFloatEncoding = encoding_for_ctype(CGFloat) # Special case so that NSImage.initWithCGImage_size_() will work. CGImageEncoding = b'{CGImage=}' NSZoneEncoding = b'{_NSZone=}' # from /System/Library/Frameworks/Foundation.framework/Headers/NSGeometry.h class NSPoint(Structure): _fields_ = [ ("x", CGFloat), ("y", CGFloat) ] CGPoint = NSPoint class NSSize(Structure): _fields_ = [ ("width", CGFloat), ("height", CGFloat) ] CGSize = NSSize class NSRect(Structure): _fields_ = [ ("origin", NSPoint), ("size", NSSize) ] CGRect = NSRect def NSMakeSize(w, h): return NSSize(w, h) def NSMakeRect(x, y, w, h): return NSRect(NSPoint(x, y), NSSize(w, h)) # NSDate.h NSTimeInterval = c_double CFIndex = c_long UniChar = c_ushort unichar = c_wchar # (actually defined as c_ushort in NSString.h, but need ctypes to convert properly) CGGlyph = c_ushort # CFRange struct defined in CFBase.h # This replaces the CFRangeMake(LOC, LEN) macro. class CFRange(Structure): _fields_ = [ ("location", CFIndex), ("length", CFIndex) ] # NSRange.h (Note, not defined the same as CFRange) class NSRange(Structure): _fields_ = [ ("location", NSUInteger), ("length", NSUInteger) ] NSZeroPoint = NSPoint(0,0) CFTypeID = c_ulong CFNumberType = c_uint32
Python
from ctypes import * from ctypes import util from .runtime import send_message, ObjCInstance from .cocoatypes import * ###################################################################### # CORE FOUNDATION cf = cdll.LoadLibrary(util.find_library('CoreFoundation')) kCFStringEncodingUTF8 = 0x08000100 CFAllocatorRef = c_void_p CFStringEncoding = c_uint32 cf.CFStringCreateWithCString.restype = c_void_p cf.CFStringCreateWithCString.argtypes = [CFAllocatorRef, c_char_p, CFStringEncoding] cf.CFRelease.restype = c_void_p cf.CFRelease.argtypes = [c_void_p] cf.CFStringGetLength.restype = CFIndex cf.CFStringGetLength.argtypes = [c_void_p] cf.CFStringGetMaximumSizeForEncoding.restype = CFIndex cf.CFStringGetMaximumSizeForEncoding.argtypes = [CFIndex, CFStringEncoding] cf.CFStringGetCString.restype = c_bool cf.CFStringGetCString.argtypes = [c_void_p, c_char_p, CFIndex, CFStringEncoding] cf.CFStringGetTypeID.restype = CFTypeID cf.CFStringGetTypeID.argtypes = [] cf.CFAttributedStringCreate.restype = c_void_p cf.CFAttributedStringCreate.argtypes = [CFAllocatorRef, c_void_p, c_void_p] # Core Foundation type to Python type conversion functions def CFSTR(string): return ObjCInstance(c_void_p(cf.CFStringCreateWithCString( None, string.encode('utf8'), kCFStringEncodingUTF8))) # Other possible names for this method: # at, ampersat, arobe, apenstaartje (little monkey tail), strudel, # klammeraffe (spider monkey), little_mouse, arroba, sobachka (doggie) # malpa (monkey), snabel (trunk), papaki (small duck), afna (monkey), # kukac (caterpillar). def get_NSString(string): """Autoreleased version of CFSTR""" return CFSTR(string).autorelease() def cfstring_to_string(cfstring): length = cf.CFStringGetLength(cfstring) size = cf.CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) buffer = c_buffer(size + 1) result = cf.CFStringGetCString(cfstring, buffer, len(buffer), kCFStringEncodingUTF8) if result: return unicode(buffer.value, 'utf-8') cf.CFDataCreate.restype = c_void_p cf.CFDataCreate.argtypes = [c_void_p, c_void_p, CFIndex] cf.CFDataGetBytes.restype = None cf.CFDataGetBytes.argtypes = [c_void_p, CFRange, c_void_p] cf.CFDataGetLength.restype = CFIndex cf.CFDataGetLength.argtypes = [c_void_p] cf.CFDictionaryGetValue.restype = c_void_p cf.CFDictionaryGetValue.argtypes = [c_void_p, c_void_p] cf.CFDictionaryAddValue.restype = None cf.CFDictionaryAddValue.argtypes = [c_void_p, c_void_p, c_void_p] cf.CFDictionaryCreateMutable.restype = c_void_p cf.CFDictionaryCreateMutable.argtypes = [CFAllocatorRef, CFIndex, c_void_p, c_void_p] cf.CFNumberCreate.restype = c_void_p cf.CFNumberCreate.argtypes = [CFAllocatorRef, CFNumberType, c_void_p] cf.CFNumberGetType.restype = CFNumberType cf.CFNumberGetType.argtypes = [c_void_p] cf.CFNumberGetValue.restype = c_ubyte cf.CFNumberGetValue.argtypes = [c_void_p, CFNumberType, c_void_p] cf.CFNumberGetTypeID.restype = CFTypeID cf.CFNumberGetTypeID.argtypes = [] cf.CFGetTypeID.restype = CFTypeID cf.CFGetTypeID.argtypes = [c_void_p] # CFNumber.h kCFNumberSInt8Type = 1 kCFNumberSInt16Type = 2 kCFNumberSInt32Type = 3 kCFNumberSInt64Type = 4 kCFNumberFloat32Type = 5 kCFNumberFloat64Type = 6 kCFNumberCharType = 7 kCFNumberShortType = 8 kCFNumberIntType = 9 kCFNumberLongType = 10 kCFNumberLongLongType = 11 kCFNumberFloatType = 12 kCFNumberDoubleType = 13 kCFNumberCFIndexType = 14 kCFNumberNSIntegerType = 15 kCFNumberCGFloatType = 16 kCFNumberMaxType = 16 def cfnumber_to_number(cfnumber): """Convert CFNumber to python int or float.""" numeric_type = cf.CFNumberGetType(cfnumber) cfnum_to_ctype = {kCFNumberSInt8Type:c_int8, kCFNumberSInt16Type:c_int16, kCFNumberSInt32Type:c_int32, kCFNumberSInt64Type:c_int64, kCFNumberFloat32Type:c_float, kCFNumberFloat64Type:c_double, kCFNumberCharType:c_byte, kCFNumberShortType:c_short, kCFNumberIntType:c_int, kCFNumberLongType:c_long, kCFNumberLongLongType:c_longlong, kCFNumberFloatType:c_float, kCFNumberDoubleType:c_double, kCFNumberCFIndexType:CFIndex, kCFNumberCGFloatType:CGFloat} if numeric_type in cfnum_to_ctype: t = cfnum_to_ctype[numeric_type] result = t() if cf.CFNumberGetValue(cfnumber, numeric_type, byref(result)): return result.value else: raise Exception('cfnumber_to_number: unhandled CFNumber type %d' % numeric_type) # Dictionary of cftypes matched to the method converting them to python values. known_cftypes = { cf.CFStringGetTypeID() : cfstring_to_string, cf.CFNumberGetTypeID() : cfnumber_to_number } def cftype_to_value(cftype): """Convert a CFType into an equivalent python type. The convertible CFTypes are taken from the known_cftypes dictionary, which may be added to if another library implements its own conversion methods.""" if not cftype: return None typeID = cf.CFGetTypeID(cftype) if typeID in known_cftypes: convert_function = known_cftypes[typeID] return convert_function(cftype) else: return cftype cf.CFSetGetCount.restype = CFIndex cf.CFSetGetCount.argtypes = [c_void_p] cf.CFSetGetValues.restype = None # PyPy 1.7 is fine with 2nd arg as POINTER(c_void_p), # but CPython ctypes 1.1.0 complains, so just use c_void_p. cf.CFSetGetValues.argtypes = [c_void_p, c_void_p] def cfset_to_set(cfset): """Convert CFSet to python set.""" count = cf.CFSetGetCount(cfset) buffer = (c_void_p * count)() cf.CFSetGetValues(cfset, byref(buffer)) return set([ cftype_to_value(c_void_p(buffer[i])) for i in range(count) ]) cf.CFArrayGetCount.restype = CFIndex cf.CFArrayGetCount.argtypes = [c_void_p] cf.CFArrayGetValueAtIndex.restype = c_void_p cf.CFArrayGetValueAtIndex.argtypes = [c_void_p, CFIndex] def cfarray_to_list(cfarray): """Convert CFArray to python list.""" count = cf.CFArrayGetCount(cfarray) return [ cftype_to_value(c_void_p(cf.CFArrayGetValueAtIndex(cfarray, i))) for i in range(count) ] kCFRunLoopDefaultMode = c_void_p.in_dll(cf, 'kCFRunLoopDefaultMode') cf.CFRunLoopGetCurrent.restype = c_void_p cf.CFRunLoopGetCurrent.argtypes = [] cf.CFRunLoopGetMain.restype = c_void_p cf.CFRunLoopGetMain.argtypes = [] ###################################################################### # APPLICATION KIT # Even though we don't use this directly, it must be loaded so that # we can find the NSApplication, NSWindow, and NSView classes. appkit = cdll.LoadLibrary(util.find_library('AppKit')) NSDefaultRunLoopMode = c_void_p.in_dll(appkit, 'NSDefaultRunLoopMode') NSEventTrackingRunLoopMode = c_void_p.in_dll(appkit, 'NSEventTrackingRunLoopMode') NSApplicationDidHideNotification = c_void_p.in_dll(appkit, 'NSApplicationDidHideNotification') NSApplicationDidUnhideNotification = c_void_p.in_dll(appkit, 'NSApplicationDidUnhideNotification') # /System/Library/Frameworks/AppKit.framework/Headers/NSEvent.h NSAnyEventMask = 0xFFFFFFFFL # NSUIntegerMax NSKeyDown = 10 NSKeyUp = 11 NSFlagsChanged = 12 NSApplicationDefined = 15 NSAlphaShiftKeyMask = 1 << 16 NSShiftKeyMask = 1 << 17 NSControlKeyMask = 1 << 18 NSAlternateKeyMask = 1 << 19 NSCommandKeyMask = 1 << 20 NSNumericPadKeyMask = 1 << 21 NSHelpKeyMask = 1 << 22 NSFunctionKeyMask = 1 << 23 NSInsertFunctionKey = 0xF727 NSDeleteFunctionKey = 0xF728 NSHomeFunctionKey = 0xF729 NSBeginFunctionKey = 0xF72A NSEndFunctionKey = 0xF72B NSPageUpFunctionKey = 0xF72C NSPageDownFunctionKey = 0xF72D # /System/Library/Frameworks/AppKit.framework/Headers/NSWindow.h NSBorderlessWindowMask = 0 NSTitledWindowMask = 1 << 0 NSClosableWindowMask = 1 << 1 NSMiniaturizableWindowMask = 1 << 2 NSResizableWindowMask = 1 << 3 # /System/Library/Frameworks/AppKit.framework/Headers/NSPanel.h NSUtilityWindowMask = 1 << 4 # /System/Library/Frameworks/AppKit.framework/Headers/NSGraphics.h NSBackingStoreRetained = 0 NSBackingStoreNonretained = 1 NSBackingStoreBuffered = 2 # /System/Library/Frameworks/AppKit.framework/Headers/NSTrackingArea.h NSTrackingMouseEnteredAndExited = 0x01 NSTrackingMouseMoved = 0x02 NSTrackingCursorUpdate = 0x04 NSTrackingActiveInActiveApp = 0x40 # /System/Library/Frameworks/AppKit.framework/Headers/NSOpenGL.h NSOpenGLPFAAllRenderers = 1 # choose from all available renderers NSOpenGLPFADoubleBuffer = 5 # choose a double buffered pixel format NSOpenGLPFAStereo = 6 # stereo buffering supported NSOpenGLPFAAuxBuffers = 7 # number of aux buffers NSOpenGLPFAColorSize = 8 # number of color buffer bits NSOpenGLPFAAlphaSize = 11 # number of alpha component bits NSOpenGLPFADepthSize = 12 # number of depth buffer bits NSOpenGLPFAStencilSize = 13 # number of stencil buffer bits NSOpenGLPFAAccumSize = 14 # number of accum buffer bits NSOpenGLPFAMinimumPolicy = 51 # never choose smaller buffers than requested NSOpenGLPFAMaximumPolicy = 52 # choose largest buffers of type requested NSOpenGLPFAOffScreen = 53 # choose an off-screen capable renderer NSOpenGLPFAFullScreen = 54 # choose a full-screen capable renderer NSOpenGLPFASampleBuffers = 55 # number of multi sample buffers NSOpenGLPFASamples = 56 # number of samples per multi sample buffer NSOpenGLPFAAuxDepthStencil = 57 # each aux buffer has its own depth stencil NSOpenGLPFAColorFloat = 58 # color buffers store floating point pixels NSOpenGLPFAMultisample = 59 # choose multisampling NSOpenGLPFASupersample = 60 # choose supersampling NSOpenGLPFASampleAlpha = 61 # request alpha filtering NSOpenGLPFARendererID = 70 # request renderer by ID NSOpenGLPFASingleRenderer = 71 # choose a single renderer for all screens NSOpenGLPFANoRecovery = 72 # disable all failure recovery systems NSOpenGLPFAAccelerated = 73 # choose a hardware accelerated renderer NSOpenGLPFAClosestPolicy = 74 # choose the closest color buffer to request NSOpenGLPFARobust = 75 # renderer does not need failure recovery NSOpenGLPFABackingStore = 76 # back buffer contents are valid after swap NSOpenGLPFAMPSafe = 78 # renderer is multi-processor safe NSOpenGLPFAWindow = 80 # can be used to render to an onscreen window NSOpenGLPFAMultiScreen = 81 # single window can span multiple screens NSOpenGLPFACompliant = 83 # renderer is opengl compliant NSOpenGLPFAScreenMask = 84 # bit mask of supported physical screens NSOpenGLPFAPixelBuffer = 90 # can be used to render to a pbuffer NSOpenGLPFARemotePixelBuffer = 91 # can be used to render offline to a pbuffer NSOpenGLPFAAllowOfflineRenderers = 96 # allow use of offline renderers NSOpenGLPFAAcceleratedCompute = 97 # choose a hardware accelerated compute device NSOpenGLPFAVirtualScreenCount = 128 # number of virtual screens in this format NSOpenGLCPSwapInterval = 222 # /System/Library/Frameworks/ApplicationServices.framework/Frameworks/... # CoreGraphics.framework/Headers/CGImage.h kCGImageAlphaNone = 0 kCGImageAlphaPremultipliedLast = 1 kCGImageAlphaPremultipliedFirst = 2 kCGImageAlphaLast = 3 kCGImageAlphaFirst = 4 kCGImageAlphaNoneSkipLast = 5 kCGImageAlphaNoneSkipFirst = 6 kCGImageAlphaOnly = 7 kCGImageAlphaPremultipliedLast = 1 kCGBitmapAlphaInfoMask = 0x1F kCGBitmapFloatComponents = 1 << 8 kCGBitmapByteOrderMask = 0x7000 kCGBitmapByteOrderDefault = 0 << 12 kCGBitmapByteOrder16Little = 1 << 12 kCGBitmapByteOrder32Little = 2 << 12 kCGBitmapByteOrder16Big = 3 << 12 kCGBitmapByteOrder32Big = 4 << 12 # NSApplication.h NSApplicationPresentationDefault = 0 NSApplicationPresentationHideDock = 1 << 1 NSApplicationPresentationHideMenuBar = 1 << 3 NSApplicationPresentationDisableProcessSwitching = 1 << 5 NSApplicationPresentationDisableHideApplication = 1 << 8 # NSRunningApplication.h NSApplicationActivationPolicyRegular = 0 NSApplicationActivationPolicyAccessory = 1 NSApplicationActivationPolicyProhibited = 2 ###################################################################### # QUARTZ / COREGRAPHICS quartz = cdll.LoadLibrary(util.find_library('quartz')) CGDirectDisplayID = c_uint32 # CGDirectDisplay.h CGError = c_int32 # CGError.h CGBitmapInfo = c_uint32 # CGImage.h # /System/Library/Frameworks/ApplicationServices.framework/Frameworks/... # ImageIO.framework/Headers/CGImageProperties.h kCGImagePropertyGIFDictionary = c_void_p.in_dll(quartz, 'kCGImagePropertyGIFDictionary') kCGImagePropertyGIFDelayTime = c_void_p.in_dll(quartz, 'kCGImagePropertyGIFDelayTime') # /System/Library/Frameworks/ApplicationServices.framework/Frameworks/... # CoreGraphics.framework/Headers/CGColorSpace.h kCGRenderingIntentDefault = 0 quartz.CGDisplayIDToOpenGLDisplayMask.restype = c_uint32 quartz.CGDisplayIDToOpenGLDisplayMask.argtypes = [c_uint32] quartz.CGMainDisplayID.restype = CGDirectDisplayID quartz.CGMainDisplayID.argtypes = [] quartz.CGShieldingWindowLevel.restype = c_int32 quartz.CGShieldingWindowLevel.argtypes = [] quartz.CGCursorIsVisible.restype = c_bool quartz.CGDisplayCopyAllDisplayModes.restype = c_void_p quartz.CGDisplayCopyAllDisplayModes.argtypes = [CGDirectDisplayID, c_void_p] quartz.CGDisplaySetDisplayMode.restype = CGError quartz.CGDisplaySetDisplayMode.argtypes = [CGDirectDisplayID, c_void_p, c_void_p] quartz.CGDisplayCapture.restype = CGError quartz.CGDisplayCapture.argtypes = [CGDirectDisplayID] quartz.CGDisplayRelease.restype = CGError quartz.CGDisplayRelease.argtypes = [CGDirectDisplayID] quartz.CGDisplayCopyDisplayMode.restype = c_void_p quartz.CGDisplayCopyDisplayMode.argtypes = [CGDirectDisplayID] quartz.CGDisplayModeGetRefreshRate.restype = c_double quartz.CGDisplayModeGetRefreshRate.argtypes = [c_void_p] quartz.CGDisplayModeRetain.restype = c_void_p quartz.CGDisplayModeRetain.argtypes = [c_void_p] quartz.CGDisplayModeRelease.restype = None quartz.CGDisplayModeRelease.argtypes = [c_void_p] quartz.CGDisplayModeGetWidth.restype = c_size_t quartz.CGDisplayModeGetWidth.argtypes = [c_void_p] quartz.CGDisplayModeGetHeight.restype = c_size_t quartz.CGDisplayModeGetHeight.argtypes = [c_void_p] quartz.CGDisplayModeCopyPixelEncoding.restype = c_void_p quartz.CGDisplayModeCopyPixelEncoding.argtypes = [c_void_p] quartz.CGGetActiveDisplayList.restype = CGError quartz.CGGetActiveDisplayList.argtypes = [c_uint32, POINTER(CGDirectDisplayID), POINTER(c_uint32)] quartz.CGDisplayBounds.restype = CGRect quartz.CGDisplayBounds.argtypes = [CGDirectDisplayID] quartz.CGImageSourceCreateWithData.restype = c_void_p quartz.CGImageSourceCreateWithData.argtypes = [c_void_p, c_void_p] quartz.CGImageSourceCreateImageAtIndex.restype = c_void_p quartz.CGImageSourceCreateImageAtIndex.argtypes = [c_void_p, c_size_t, c_void_p] quartz.CGImageSourceCopyPropertiesAtIndex.restype = c_void_p quartz.CGImageSourceCopyPropertiesAtIndex.argtypes = [c_void_p, c_size_t, c_void_p] quartz.CGImageGetDataProvider.restype = c_void_p quartz.CGImageGetDataProvider.argtypes = [c_void_p] quartz.CGDataProviderCopyData.restype = c_void_p quartz.CGDataProviderCopyData.argtypes = [c_void_p] quartz.CGDataProviderCreateWithCFData.restype = c_void_p quartz.CGDataProviderCreateWithCFData.argtypes = [c_void_p] quartz.CGImageCreate.restype = c_void_p quartz.CGImageCreate.argtypes = [c_size_t, c_size_t, c_size_t, c_size_t, c_size_t, c_void_p, c_uint32, c_void_p, c_void_p, c_bool, c_int] quartz.CGImageRelease.restype = None quartz.CGImageRelease.argtypes = [c_void_p] quartz.CGImageGetBytesPerRow.restype = c_size_t quartz.CGImageGetBytesPerRow.argtypes = [c_void_p] quartz.CGImageGetWidth.restype = c_size_t quartz.CGImageGetWidth.argtypes = [c_void_p] quartz.CGImageGetHeight.restype = c_size_t quartz.CGImageGetHeight.argtypes = [c_void_p] quartz.CGImageGetBitsPerPixel.restype = c_size_t quartz.CGImageGetBitsPerPixel.argtypes = [c_void_p] quartz.CGImageGetBitmapInfo.restype = CGBitmapInfo quartz.CGImageGetBitmapInfo.argtypes = [c_void_p] quartz.CGColorSpaceCreateDeviceRGB.restype = c_void_p quartz.CGColorSpaceCreateDeviceRGB.argtypes = [] quartz.CGDataProviderRelease.restype = None quartz.CGDataProviderRelease.argtypes = [c_void_p] quartz.CGColorSpaceRelease.restype = None quartz.CGColorSpaceRelease.argtypes = [c_void_p] quartz.CGWarpMouseCursorPosition.restype = CGError quartz.CGWarpMouseCursorPosition.argtypes = [CGPoint] quartz.CGDisplayMoveCursorToPoint.restype = CGError quartz.CGDisplayMoveCursorToPoint.argtypes = [CGDirectDisplayID, CGPoint] quartz.CGAssociateMouseAndMouseCursorPosition.restype = CGError quartz.CGAssociateMouseAndMouseCursorPosition.argtypes = [c_bool] quartz.CGBitmapContextCreate.restype = c_void_p quartz.CGBitmapContextCreate.argtypes = [c_void_p, c_size_t, c_size_t, c_size_t, c_size_t, c_void_p, CGBitmapInfo] quartz.CGBitmapContextCreateImage.restype = c_void_p quartz.CGBitmapContextCreateImage.argtypes = [c_void_p] quartz.CGFontCreateWithDataProvider.restype = c_void_p quartz.CGFontCreateWithDataProvider.argtypes = [c_void_p] quartz.CGFontCreateWithFontName.restype = c_void_p quartz.CGFontCreateWithFontName.argtypes = [c_void_p] quartz.CGContextDrawImage.restype = None quartz.CGContextDrawImage.argtypes = [c_void_p, CGRect, c_void_p] quartz.CGContextRelease.restype = None quartz.CGContextRelease.argtypes = [c_void_p] quartz.CGContextSetTextPosition.restype = None quartz.CGContextSetTextPosition.argtypes = [c_void_p, CGFloat, CGFloat] quartz.CGContextSetShouldAntialias.restype = None quartz.CGContextSetShouldAntialias.argtypes = [c_void_p, c_bool] ###################################################################### # CORETEXT ct = cdll.LoadLibrary(util.find_library('CoreText')) # Types CTFontOrientation = c_uint32 # CTFontDescriptor.h CTFontSymbolicTraits = c_uint32 # CTFontTraits.h # CoreText constants kCTFontAttributeName = c_void_p.in_dll(ct, 'kCTFontAttributeName') kCTFontFamilyNameAttribute = c_void_p.in_dll(ct, 'kCTFontFamilyNameAttribute') kCTFontSymbolicTrait = c_void_p.in_dll(ct, 'kCTFontSymbolicTrait') kCTFontWeightTrait = c_void_p.in_dll(ct, 'kCTFontWeightTrait') kCTFontTraitsAttribute = c_void_p.in_dll(ct, 'kCTFontTraitsAttribute') # constants from CTFontTraits.h kCTFontItalicTrait = (1 << 0) kCTFontBoldTrait = (1 << 1) ct.CTLineCreateWithAttributedString.restype = c_void_p ct.CTLineCreateWithAttributedString.argtypes = [c_void_p] ct.CTLineDraw.restype = None ct.CTLineDraw.argtypes = [c_void_p, c_void_p] ct.CTFontGetBoundingRectsForGlyphs.restype = CGRect ct.CTFontGetBoundingRectsForGlyphs.argtypes = [c_void_p, CTFontOrientation, POINTER(CGGlyph), POINTER(CGRect), CFIndex] ct.CTFontGetAdvancesForGlyphs.restype = c_double ct.CTFontGetAdvancesForGlyphs.argtypes = [c_void_p, CTFontOrientation, POINTER(CGGlyph), POINTER(CGSize), CFIndex] ct.CTFontGetAscent.restype = CGFloat ct.CTFontGetAscent.argtypes = [c_void_p] ct.CTFontGetDescent.restype = CGFloat ct.CTFontGetDescent.argtypes = [c_void_p] ct.CTFontGetSymbolicTraits.restype = CTFontSymbolicTraits ct.CTFontGetSymbolicTraits.argtypes = [c_void_p] ct.CTFontGetGlyphsForCharacters.restype = c_bool ct.CTFontGetGlyphsForCharacters.argtypes = [c_void_p, POINTER(UniChar), POINTER(CGGlyph), CFIndex] ct.CTFontCreateWithGraphicsFont.restype = c_void_p ct.CTFontCreateWithGraphicsFont.argtypes = [c_void_p, CGFloat, c_void_p, c_void_p] ct.CTFontCopyFamilyName.restype = c_void_p ct.CTFontCopyFamilyName.argtypes = [c_void_p] ct.CTFontCopyFullName.restype = c_void_p ct.CTFontCopyFullName.argtypes = [c_void_p] ct.CTFontCreateWithFontDescriptor.restype = c_void_p ct.CTFontCreateWithFontDescriptor.argtypes = [c_void_p, CGFloat, c_void_p] ct.CTFontDescriptorCreateWithAttributes.restype = c_void_p ct.CTFontDescriptorCreateWithAttributes.argtypes = [c_void_p] ###################################################################### # FOUNDATION foundation = cdll.LoadLibrary(util.find_library('Foundation')) foundation.NSMouseInRect.restype = c_bool foundation.NSMouseInRect.argtypes = [NSPoint, NSRect, c_bool]
Python
# objective-ctypes # # Copyright (c) 2011, Phillip Nguyen # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # Neither the name of objective-ctypes nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from .runtime import objc, send_message, send_super from .runtime import get_selector from .runtime import ObjCClass, ObjCInstance, ObjCSubclass from .cocoatypes import * from .cocoalibs import *
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '' from pyglet.window import key # From SDL: src/video/quartz/SDL_QuartzKeys.h # These are the Macintosh key scancode constants -- from Inside Macintosh # http://boredzo.org/blog/wp-content/uploads/2007/05/imtx-virtual-keycodes.png # Renamed QZ_RALT, QZ_LALT to QZ_ROPTION, QZ_LOPTION # and QZ_RMETA, QZ_LMETA to QZ_RCOMMAND, QZ_LCOMMAND. # # See also: # /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Headers/Events.h QZ_ESCAPE = 0x35 QZ_F1 = 0x7A QZ_F2 = 0x78 QZ_F3 = 0x63 QZ_F4 = 0x76 QZ_F5 = 0x60 QZ_F6 = 0x61 QZ_F7 = 0x62 QZ_F8 = 0x64 QZ_F9 = 0x65 QZ_F10 = 0x6D QZ_F11 = 0x67 QZ_F12 = 0x6F QZ_F13 = 0x69 QZ_F14 = 0x6B QZ_F15 = 0x71 QZ_F16 = 0x6A QZ_F17 = 0x40 QZ_F18 = 0x4F QZ_F19 = 0x50 QZ_F20 = 0x5A QZ_BACKQUOTE = 0x32 QZ_1 = 0x12 QZ_2 = 0x13 QZ_3 = 0x14 QZ_4 = 0x15 QZ_5 = 0x17 QZ_6 = 0x16 QZ_7 = 0x1A QZ_8 = 0x1C QZ_9 = 0x19 QZ_0 = 0x1D QZ_MINUS = 0x1B QZ_EQUALS = 0x18 QZ_BACKSPACE = 0x33 QZ_INSERT = 0x72 QZ_HOME = 0x73 QZ_PAGEUP = 0x74 QZ_NUMLOCK = 0x47 QZ_KP_EQUALS = 0x51 QZ_KP_DIVIDE = 0x4B QZ_KP_MULTIPLY = 0x43 QZ_TAB = 0x30 QZ_q = 0x0C QZ_w = 0x0D QZ_e = 0x0E QZ_r = 0x0F QZ_t = 0x11 QZ_y = 0x10 QZ_u = 0x20 QZ_i = 0x22 QZ_o = 0x1F QZ_p = 0x23 QZ_LEFTBRACKET = 0x21 QZ_RIGHTBRACKET = 0x1E QZ_BACKSLASH = 0x2A QZ_DELETE = 0x75 QZ_END = 0x77 QZ_PAGEDOWN = 0x79 QZ_KP7 = 0x59 QZ_KP8 = 0x5B QZ_KP9 = 0x5C QZ_KP_MINUS = 0x4E QZ_CAPSLOCK = 0x39 QZ_a = 0x00 QZ_s = 0x01 QZ_d = 0x02 QZ_f = 0x03 QZ_g = 0x05 QZ_h = 0x04 QZ_j = 0x26 QZ_k = 0x28 QZ_l = 0x25 QZ_SEMICOLON = 0x29 QZ_QUOTE = 0x27 QZ_RETURN = 0x24 QZ_KP4 = 0x56 QZ_KP5 = 0x57 QZ_KP6 = 0x58 QZ_KP_PLUS = 0x45 QZ_LSHIFT = 0x38 QZ_z = 0x06 QZ_x = 0x07 QZ_c = 0x08 QZ_v = 0x09 QZ_b = 0x0B QZ_n = 0x2D QZ_m = 0x2E QZ_COMMA = 0x2B QZ_PERIOD = 0x2F QZ_SLASH = 0x2C QZ_RSHIFT = 0x3C QZ_UP = 0x7E QZ_KP1 = 0x53 QZ_KP2 = 0x54 QZ_KP3 = 0x55 QZ_KP_ENTER = 0x4C QZ_LCTRL = 0x3B QZ_LOPTION = 0x3A QZ_LCOMMAND = 0x37 QZ_SPACE = 0x31 QZ_RCOMMAND = 0x36 QZ_ROPTION = 0x3D QZ_RCTRL = 0x3E QZ_FUNCTION = 0x3F QZ_LEFT = 0x7B QZ_DOWN = 0x7D QZ_RIGHT = 0x7C QZ_KP0 = 0x52 QZ_KP_PERIOD = 0x41 keymap = { QZ_ESCAPE: key.ESCAPE, QZ_F1: key.F1, QZ_F2: key.F2, QZ_F3: key.F3, QZ_F4: key.F4, QZ_F5: key.F5, QZ_F6: key.F6, QZ_F7: key.F7, QZ_F8: key.F8, QZ_F9: key.F9, QZ_F10: key.F10, QZ_F11: key.F11, QZ_F12: key.F12, QZ_F13: key.F13, QZ_F14: key.F14, QZ_F15: key.F15, QZ_F16: key.F16, QZ_F17: key.F17, QZ_F18: key.F18, QZ_F19: key.F19, QZ_F20: key.F20, QZ_BACKQUOTE: key.QUOTELEFT, QZ_1: key._1, QZ_2: key._2, QZ_3: key._3, QZ_4: key._4, QZ_5: key._5, QZ_6: key._6, QZ_7: key._7, QZ_8: key._8, QZ_9: key._9, QZ_0: key._0, QZ_MINUS: key.MINUS, QZ_EQUALS: key.EQUAL, QZ_BACKSPACE: key.BACKSPACE, QZ_INSERT: key.INSERT, QZ_HOME: key.HOME, QZ_PAGEUP: key.PAGEUP, QZ_NUMLOCK: key.NUMLOCK, QZ_KP_EQUALS: key.NUM_EQUAL, QZ_KP_DIVIDE: key.NUM_DIVIDE, QZ_KP_MULTIPLY: key.NUM_MULTIPLY, QZ_TAB: key.TAB, QZ_q: key.Q, QZ_w: key.W, QZ_e: key.E, QZ_r: key.R, QZ_t: key.T, QZ_y: key.Y, QZ_u: key.U, QZ_i: key.I, QZ_o: key.O, QZ_p: key.P, QZ_LEFTBRACKET: key.BRACKETLEFT, QZ_RIGHTBRACKET: key.BRACKETRIGHT, QZ_BACKSLASH: key.BACKSLASH, QZ_DELETE: key.DELETE, QZ_END: key.END, QZ_PAGEDOWN: key.PAGEDOWN, QZ_KP7: key.NUM_7, QZ_KP8: key.NUM_8, QZ_KP9: key.NUM_9, QZ_KP_MINUS: key.NUM_SUBTRACT, QZ_CAPSLOCK: key.CAPSLOCK, QZ_a: key.A, QZ_s: key.S, QZ_d: key.D, QZ_f: key.F, QZ_g: key.G, QZ_h: key.H, QZ_j: key.J, QZ_k: key.K, QZ_l: key.L, QZ_SEMICOLON: key.SEMICOLON, QZ_QUOTE: key.APOSTROPHE, QZ_RETURN: key.RETURN, QZ_KP4: key.NUM_4, QZ_KP5: key.NUM_5, QZ_KP6: key.NUM_6, QZ_KP_PLUS: key.NUM_ADD, QZ_LSHIFT: key.LSHIFT, QZ_z: key.Z, QZ_x: key.X, QZ_c: key.C, QZ_v: key.V, QZ_b: key.B, QZ_n: key.N, QZ_m: key.M, QZ_COMMA: key.COMMA, QZ_PERIOD: key.PERIOD, QZ_SLASH: key.SLASH, QZ_RSHIFT: key.RSHIFT, QZ_UP: key.UP, QZ_KP1: key.NUM_1, QZ_KP2: key.NUM_2, QZ_KP3: key.NUM_3, QZ_KP_ENTER: key.NUM_ENTER, QZ_LCTRL: key.LCTRL, QZ_LOPTION: key.LOPTION, QZ_LCOMMAND: key.LCOMMAND, QZ_SPACE: key.SPACE, QZ_RCOMMAND: key.RCOMMAND, QZ_ROPTION: key.ROPTION, QZ_RCTRL: key.RCTRL, QZ_FUNCTION: key.FUNCTION, QZ_LEFT: key.LEFT, QZ_DOWN: key.DOWN, QZ_RIGHT: key.RIGHT, QZ_KP0: key.NUM_0, QZ_KP_PERIOD: key.NUM_DECIMAL, } charmap = { ' ' : key.SPACE, '!' : key.EXCLAMATION, '"' : key.DOUBLEQUOTE, '#' : key.HASH, '#' : key.POUND, '$' : key.DOLLAR, '%' : key.PERCENT, '&' : key.AMPERSAND, "'" : key.APOSTROPHE, '(' : key.PARENLEFT, ')' : key.PARENRIGHT, '*' : key.ASTERISK, '+' : key.PLUS, ',' : key.COMMA, '-' : key.MINUS, '.' : key.PERIOD, '/' : key.SLASH, '0' : key._0, '1' : key._1, '2' : key._2, '3' : key._3, '4' : key._4, '5' : key._5, '6' : key._6, '7' : key._7, '8' : key._8, '9' : key._9, ':' : key.COLON, ';' : key.SEMICOLON, '<' : key.LESS, '=' : key.EQUAL, '>' : key.GREATER, '?' : key.QUESTION, '@' : key.AT, '[' : key.BRACKETLEFT, '\\' : key.BACKSLASH, ']' : key.BRACKETRIGHT, '^' : key.ASCIICIRCUM, '_' : key.UNDERSCORE, '`' : key.GRAVE, '`' : key.QUOTELEFT, 'A' : key.A, 'B' : key.B, 'C' : key.C, 'D' : key.D, 'E' : key.E, 'F' : key.F, 'G' : key.G, 'H' : key.H, 'I' : key.I, 'J' : key.J, 'K' : key.K, 'L' : key.L, 'M' : key.M, 'N' : key.N, 'O' : key.O, 'P' : key.P, 'Q' : key.Q, 'R' : key.R, 'S' : key.S, 'T' : key.T, 'U' : key.U, 'V' : key.V, 'W' : key.W, 'X' : key.X, 'Y' : key.Y, 'Z' : key.Z, '{' : key.BRACELEFT, '|' : key.BAR, '}' : key.BRACERIGHT, '~' : key.ASCIITILDE }
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from ctypes import * Boolean = c_ubyte # actually an unsigned char Fixed = c_int32 ItemCount = c_uint32 ByteOffset = ByteCount = c_uint32 class Rect(Structure): _fields_ = [ ('top', c_short), ('left', c_short), ('bottom', c_short), ('right', c_short) ] class Point(Structure): _fields_ = [ ('v', c_short), ('h', c_short), ] class CGPoint(Structure): _fields_ = [ ('x', c_float), ('y', c_float), ] class CGSize(Structure): _fields_ = [ ('width', c_float), ('height', c_float) ] class CGRect(Structure): _fields_ = [ ('origin', CGPoint), ('size', CGSize) ] __slots__ = ['origin', 'size'] CGDirectDisplayID = c_void_p CGDisplayCount = c_uint32 CGTableCount = c_uint32 CGDisplayCoord = c_int32 CGByteValue = c_ubyte CGOpenGLDisplayMask = c_uint32 CGRefreshRate = c_double CGCaptureOptions = c_uint32 HIPoint = CGPoint HISize = CGSize HIRect = CGRect class EventTypeSpec(Structure): _fields_ = [ ('eventClass', c_uint32), ('eventKind', c_uint32) ] WindowRef = c_void_p EventRef = c_void_p EventTargetRef = c_void_p EventHandlerRef = c_void_p MenuRef = c_void_p MenuID = c_int16 MenuItemIndex = c_uint16 MenuCommand = c_uint32 CFStringEncoding = c_uint WindowClass = c_uint32 WindowAttributes = c_uint32 WindowPositionMethod = c_uint32 EventMouseButton = c_uint16 EventMouseWheelAxis = c_uint16 OSType = c_uint32 OSStatus = c_int32 class MouseTrackingRegionID(Structure): _fields_ = [('signature', OSType), ('id', c_int32)] MouseTrackingRef = c_void_p RgnHandle = c_void_p class ProcessSerialNumber(Structure): _fields_ = [('highLongOfPSN', c_uint32), ('lowLongOfPSN', c_uint32)] class HICommand_Menu(Structure): _fields_ = [ ('menuRef', MenuRef), ('menuItemIndex', MenuItemIndex), ] class HICommand(Structure): _fields_ = [ ('attributes', c_uint32), ('commandID', c_uint32), ('menu', HICommand_Menu) ] class EventRecord(Structure): _fields_ = [ ('what', c_uint16), ('message', c_uint32), ('when', c_uint32), ('where', Point), ('modifiers', c_uint16) ] class RGBColor(Structure): _fields_ = [ ('red', c_ushort), ('green', c_ushort), ('blue', c_ushort) ] class TabletProximityRec(Structure): _fields_ = ( ('vendorID', c_uint16), ('tabletID', c_uint16), ('pointerID', c_uint16), ('deviceID', c_uint16), ('systemTabletID', c_uint16), ('vendorPointerType', c_uint16), ('pointerSerialNumber', c_uint32), ('uniqueID', c_uint64), ('capabilityMask', c_uint32), ('pointerType', c_uint8), ('enterProximity', c_uint8), ) class TabletPointRec(Structure): _fields_ = ( ('absX', c_int32), ('absY', c_int32), ('absZ', c_int32), ('buttons', c_uint16), ('pressure', c_uint16), ('tiltX', c_int16), ('tiltY', c_int16), ('rotation', c_uint16), ('tangentialPressure', c_int16), ('deviceID', c_uint16), ('vendor1', c_int16), ('vendor2', c_int16), ('vendor3', c_int16), )
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' # CFString.h kCFStringEncodingMacRoman = 0 kCFStringEncodingWindowsLatin1 = 0x0500 kCFStringEncodingISOLatin1 = 0x0201 kCFStringEncodingNextStepLatin = 0x0B01 kCFStringEncodingASCII = 0x0600 kCFStringEncodingUnicode = 0x0100 kCFStringEncodingUTF8 = 0x08000100 kCFStringEncodingNonLossyASCII = 0x0BFF # MacTypes.h noErr = 0 # CarbonEventsCore.h eventLoopTimedOutErr = -9875 eventLoopQuitErr = -9876 kEventPriorityStandard = 1 # MacApplication.h kUIModeNormal = 0 kUIModeContentSuppressed = 1 kUIModeContentHidden = 2 kUIModeAllSuppressed = 4 kUIModeAllHidden = 3 kUIOptionAutoShowMenuBar = 1 << 0 kUIOptionDisableAppleMenu = 1 << 2 kUIOptionDisableProcessSwitch = 1 << 3 kUIOptionDisableForceQuit = 1 << 4 kUIOptionDisableSessionTerminate = 1 << 5 kUIOptionDisableHide = 1 << 6 # MacWindows.h kAlertWindowClass = 1 kMovableAlertWindowClass = 2 kModalWindowClass = 3 kMovableModalWindowClass = 4 kFloatingWindowClass = 5 kDocumentWindowClass = 6 kUtilityWindowClass = 8 kHelpWindowClass = 10 kSheetWindowClass = 11 kToolbarWindowClass = 12 kPlainWindowClass = 13 kOverlayWindowClass = 14 kSheetAlertWindowClass = 15 kAltPlainWindowClass = 16 kSimpleWindowClass = 18 # no window frame kDrawerWindowClass = 20 kWindowNoAttributes = 0x0 kWindowCloseBoxAttribute = 0x1 kWindowHorizontalZoomAttribute = 0x2 kWindowVerticalZoomAttribute = 0x4 kWindowFullZoomAttribute = kWindowHorizontalZoomAttribute | \ kWindowVerticalZoomAttribute kWindowCollapseBoxAttribute = 0x8 kWindowResizableAttribute = 0x10 kWindowSideTitlebarAttribute = 0x20 kWindowToolbarAttribute = 0x40 kWindowMetalAttribute = 1 << 8 kWindowDoesNotCycleAttribute = 1 << 15 kWindowNoupdatesAttribute = 1 << 16 kWindowNoActivatesAttribute = 1 << 17 kWindowOpaqueForEventsAttribute = 1 << 18 kWindowCompositingAttribute = 1 << 19 kWindowNoShadowAttribute = 1 << 21 kWindowHideOnSuspendAttribute = 1 << 24 kWindowAsyncDragAttribute = 1 << 23 kWindowStandardHandlerAttribute = 1 << 25 kWindowHideOnFullScreenAttribute = 1 << 26 kWindowInWindowMenuAttribute = 1 << 27 kWindowLiveResizeAttribute = 1 << 28 kWindowIgnoreClicksAttribute = 1 << 29 kWindowNoConstrainAttribute = 1 << 31 kWindowStandardDocumentAttributes = kWindowCloseBoxAttribute | \ kWindowFullZoomAttribute | \ kWindowCollapseBoxAttribute | \ kWindowResizableAttribute kWindowStandardFloatingAttributes = kWindowCloseBoxAttribute | \ kWindowCollapseBoxAttribute kWindowCenterOnMainScreen = 1 kWindowCenterOnParentWindow = 2 kWindowCenterOnParentWindowScreen = 3 kWindowCascadeOnMainScreen = 4 kWindowCascadeOnParentWindow = 5 kWindowCascadeonParentWindowScreen = 6 kWindowCascadeStartAtParentWindowScreen = 10 kWindowAlertPositionOnMainScreen = 7 kWindowAlertPositionOnParentWindow = 8 kWindowAlertPositionOnParentWindowScreen = 9 kWindowTitleBarRgn = 0 kWindowTitleTextRgn = 1 kWindowCloseBoxRgn = 2 kWindowZoomBoxRgn = 3 kWindowDragRgn = 5 kWindowGrowRgn = 6 kWindowCollapseBoxRgn = 7 kWindowTitleProxyIconRgn = 8 kWindowStructureRgn = 32 kWindowContentRgn = 33 kWindowUpdateRgn = 34 kWindowOpaqueRgn = 35 kWindowGlobalPortRgn = 40 kWindowToolbarButtonRgn = 41 inDesk = 0 inNoWindow = 0 inMenuBar = 1 inSysWindow = 2 inContent = 3 inDrag = 4 inGrow = 5 inGoAway = 6 inZoomIn = 7 inZoomOut = 8 inCollapseBox = 11 inProxyIcon = 12 inToolbarButton = 13 inStructure = 15 def _name(name): return ord(name[0]) << 24 | \ ord(name[1]) << 16 | \ ord(name[2]) << 8 | \ ord(name[3]) # AEDataModel.h typeBoolean = _name('bool') typeChar = _name('TEXT') typeSInt16 = _name('shor') typeSInt32 = _name('long') typeUInt32 = _name('magn') typeSInt64 = _name('comp') typeIEEE32BitFloatingPoint = _name('sing') typeIEEE64BitFloatingPoint = _name('doub') type128BitFloatingPoint = _name('ldbl') typeDecimalStruct = _name('decm') # AERegistry.h typeUnicodeText = _name('utxt') typeStyledUnicodeText = _name('sutx') typeUTF8Text = _name('utf8') typeEncodedString = _name('encs') typeCString = _name('cstr') typePString = _name('pstr') typeEventRef = _name('evrf') # CarbonEvents.h kEventParamWindowRef = _name('wind') kEventParamWindowPartCode = _name('wpar') kEventParamGrafPort = _name('graf') kEventParamMenuRef = _name('menu') kEventParamEventRef = _name('evnt') kEventParamControlRef = _name('ctrl') kEventParamRgnHandle = _name('rgnh') kEventParamEnabled = _name('enab') kEventParamDimensions = _name('dims') kEventParamBounds = _name('boun') kEventParamAvailableBounds = _name('avlb') #kEventParamAEEventID = keyAEEventID #kEventParamAEEventClass = keyAEEventClass kEventParamCGContextRef = _name('cntx') kEventParamDeviceDepth = _name('devd') kEventParamDeviceColor = _name('devc') kEventParamMutableArray = _name('marr') kEventParamResult = _name('ansr') kEventParamMinimumSize = _name('mnsz') kEventParamMaximumSize = _name('mxsz') kEventParamAttributes = _name('attr') kEventParamReason = _name('why?') kEventParamTransactionID = _name('trns') kEventParamGDevice = _name('gdev') kEventParamIndex = _name('indx') kEventParamUserData = _name('usrd') kEventParamShape = _name('shap') typeWindowRef = _name('wind') typeWindowPartCode = _name('wpar') typeGrafPtr = _name('graf') typeGWorldPtr = _name('gwld') typeMenuRef = _name('menu') typeControlRef = _name('ctrl') typeCollection = _name('cltn') typeQDRgnHandle = _name('rgnh') typeOSStatus = _name('osst') typeCFIndex = _name('cfix') typeCGContextRef = _name('cntx') typeQDPoint = _name('QDpt') typeHICommand = _name('hcmd') typeHIPoint = _name('hipt') typeHISize = _name('hisz') typeHIRect = _name('hirc') typeHIShapeRef = _name('shap') typeVoidPtr = _name('void') typeGDHandle = _name('gdev') kCoreEventClass = _name('aevt') kEventClassMouse = _name('mous') kEventClassKeyboard = _name('keyb') kEventClassTextInput = _name('text') kEventClassApplication = _name('appl') kEventClassAppleEvent = _name('eppc') kEventClassMenu = _name('menu') kEventClassWindow = _name('wind') kEventClassControl = _name('cntl') kEventClassCommand = _name('cmds') kEventClassTablet = _name('tblt') kEventClassVolume = _name('vol ') kEventClassAppearance = _name('appm') kEventClassService = _name('serv') kEventClassToolbar = _name('tbar') kEventClassToolbarItem = _name('tbit') kEventClassToolbarItemView = _name('tbiv') kEventClassAccessibility = _name('acce') kEventClassSystem = _name('macs') kEventClassInk = _name('ink ') kEventClassTSMDocumentAccess = _name('tdac') kEventDurationForever = -1.0 # Appearance.h kThemeArrowCursor = 0 kThemeCopyArrowCursor = 1 kThemeAliasArrowCursor = 2 kThemeContextualMenuArrowCursor = 3 kThemeIBeamCursor = 4 kThemeCrossCursor = 5 kThemePlusCursor = 6 kThemeWatchCursor = 7 kThemeClosedHandCursor = 8 kThemeOpenHandCursor = 9 kThemePointingHandCursor = 10 kThemeCountingUpHandCursor = 11 kThemeCountingDownHandCursor = 12 kThemeCountingUpAndDownHandCursor = 13 kThemeSpinningCursor = 14 kThemeResizeLeftCursor = 15 kThemeResizeRightCursor = 16 kThemeResizeLeftRightCursor = 17 kThemeNotAllowedCursor = 18 kThemeResizeUpCursor = 19 kThemeResizeDownCursor = 20 kThemeResizeUpDownCursor = 21 kThemePoofCursor = 22 # AE kEventAppleEvent = 1 kEventAppQuit = 3 kAEQuitApplication = _name('quit') # Commands kEventProcessCommand = 1 kEventParamHICommand = _name('hcmd') kEventParamDirectObject = _name('----') kHICommandQuit = _name('quit') # Keyboard kEventRawKeyDown = 1 kEventRawKeyRepeat = 2 kEventRawKeyUp = 3 kEventRawKeyModifiersChanged = 4 kEventHotKeyPressed = 5 kEventHotKeyReleased = 6 kEventParamKeyCode = _name('kcod') kEventParamKeyMacCharCodes = _name('kchr') kEventParamKeyModifiers = _name('kmod') kEventParamKeyUnicodes = _name('kuni') kEventParamKeyboardType = _name('kbdt') typeEventHotKeyID = _name('hkid') activeFlagBit = 0 btnStateBit = 7 cmdKeyBit = 8 shiftKeyBit = 9 alphaLockBit = 10 optionKeyBit = 11 controlKeyBit = 12 rightShiftKeyBit = 13 rightOptionKeyBit = 14 rightControlKeyBit = 15 numLockBit = 16 activeFlag = 1 << activeFlagBit btnState = 1 << btnStateBit cmdKey = 1 << cmdKeyBit shiftKey = 1 << shiftKeyBit alphaLock = 1 << alphaLockBit optionKey = 1 << optionKeyBit controlKey = 1 << controlKeyBit rightShiftKey = 1 << rightShiftKeyBit rightOptionKey = 1 << rightOptionKeyBit rightControlKey = 1 << rightControlKeyBit numLock = 1 << numLockBit # TextInput kEventTextInputUpdateActiveInputArea = 1 kEventTextInputUnicodeForKeyEvent = 2 kEventTextInputOffsetToPos = 3 kEventTextInputPosToOffset = 4 kEventTextInputShowHideBottomWindow = 5 kEventTextInputGetSelectedText = 6 kEventTextInputUnicodeText = 7 kEventParamTextInputSendText = _name('tstx') kEventParamTextInputSendKeyboardEvent = _name('tske') # Mouse kEventMouseDown = 1 kEventMouseUp = 2 kEventMouseMoved = 5 kEventMouseDragged = 6 kEventMouseEntered = 8 kEventMouseExited = 9 kEventMouseWheelMoved = 10 kEventParamMouseLocation = _name('mloc') kEventParamWindowMouseLocation = _name('wmou') kEventParamMouseButton = _name('mbtn') kEventParamClickCount = _name('ccnt') kEventParamMouseWheelAxis = _name('mwax') kEventParamMouseWheelDelta = _name('mwdl') kEventParamMouseDelta = _name('mdta') kEventParamMouseChord = _name('chor') kEventParamTabletEventType = _name('tblt') kEventParamMouseTrackingRef = _name('mtrf') typeMouseButton = _name('mbtn') typeMouseWheelAxis = _name('mwax') typeMouseTrackingRef = _name('mtrf') kMouseTrackingOptionsLocalClip = 0 kMouseTrackingOptionsGlobalClip = 1 kEventMouseButtonPrimary = 1 kEventMouseButtonSecondary = 2 kEventMouseButtonTertiary = 3 kEventMouseWheelAxisX = 0 kEventMouseWheelAxisY = 1 DEFAULT_CREATOR_CODE = _name('PYGL') # <ah> this is registered for Pyglet # apps. register your own at: # http://developer.apple.com/datatype # Window kEventWindowUpdate = 1 kEventWindowDrawContent = 2 # -- window activation events -- kEventWindowActivated = 5 kEventWindowDeactivated = 6 kEventWindowHandleActivate = 91 kEventWindowHandleDeactivate = 92 kEventWindowGetClickActivation = 7 kEventWindowGetClickModality = 8 # -- window state change events -- kEventWindowShowing = 22 kEventWindowHiding = 23 kEventWindowShown = 24 kEventWindowHidden = 25 kEventWindowCollapsing = 86 kEventWindowCollapsed = 67 kEventWindowExpanding = 87 kEventWindowExpanded = 70 kEventWindowZoomed = 76 kEventWindowBoundsChanging = 26 kEventWindowBoundsChanged = 27 kEventWindowResizeStarted = 28 kEventWindowResizeCompleted = 29 kEventWindowDragStarted = 30 kEventWindowDragCompleted = 31 kEventWindowClosed = 73 kEventWindowTransitionStarted = 88 kEventWindowTransitionCompleted = 89 # -- window click events -- kEventWindowClickDragRgn = 32 kEventWindowClickResizeRgn = 33 kEventWindowClickCollapseRgn = 34 kEventWindowClickCloseRgn = 35 kEventWindowClickZoomRgn = 36 kEventWindowClickContentRgn = 37 kEventWindowClickProxyIconRgn = 38 kEventWindowClickToolbarButtonRgn = 41 kEventWindowClickStructureRgn = 42 # -- window cursor change events -- kEventWindowCursorChange = 40 # -- window action events -- kEventWindowCollapse = 66 kEventWindowCollapsed = 67 kEventWindowCollapseAll = 68 kEventWindowExpand = 69 kEventWindowExpanded = 70 kEventWindowExpandAll = 71 kEventWindowClose = 72 kEventWindowClosed = 73 kEventWindowCloseAll = 74 kEventWindowZoom = 75 kEventWindowZoomed = 76 kEventWindowZoomAll = 77 kEventWindowContextualMenuSelect = 78 kEventWindowPathSelect = 79 kEventWindowGetIdealSize = 80 kEventWindowGetMinimumSize = 81 kEventWindowGetMaximumSize = 82 kEventWindowConstrain = 83 kEventWindowHandleContentClick = 85 kEventWindowCollapsing = 86 kEventWindowExpanding = 87 kEventWindowTransitionStarted = 88 kEventWindowTransitionCompleted = 89 kEventWindowGetDockTileMenu = 90 kEventWindowHandleActivate = 91 kEventWindowHandleDeactivate = 92 kEventWindowProxyBeginDrag = 128 kEventWindowProxyEndDrag = 129 kEventWindowToolbarSwitchMode = 150 # -- window focus events -- kEventWindowFocusAcquired = 200 kEventWindowFocusRelinquish = 201 kEventWindowFocusContent = 202 kEventWindowFocusToolbar = 203 kEventWindowFocusDrawer = 204 # -- sheet events -- kEventWindowSheetOpening = 210 kEventWindowSheetOpened = 211 kEventWindowSheetClosing = 212 kEventWindowSheetClosed = 213 # -- drawer events -- kEventWindowDrawerOpening = 220 kEventWindowDrawerOpened = 221 kEventWindowDrawerClosing = 222 kEventWindowDrawerClosed = 223 # -- window definition events -- kEventWindowDrawFrame = 1000 kEventWindowDrawPart = 1001 kEventWindowGetRegion = 1002 kEventWindowHitTest = 1003 kEventWindowInit = 1004 kEventWindowDispose = 1005 kEventWindowDragHilite = 1006 kEventWindowModified = 1007 kEventWindowSetupProxyDragImage = 1008 kEventWindowStateChanged = 1009 kEventWindowMeasureTitle = 1010 kEventWindowDrawGrowBox = 1011 kEventWindowGetGrowImageRegion = 1012 kEventWindowPaint = 1013 # Process.h kNoProcess = 0 kSystemProcess = 1 kCurrentProcess = 2 # CGColorSpace.h kCGRenderingIntentDefault = 0 # CGImage.h kCGImageAlphaNone = 0 kCGImageAlphaPremultipliedLast = 1 kCGImageAlphaPremultipliedFirst = 2 kCGImageAlphaLast = 3 kCGImageAlphaFirst = 4 kCGImageAlphaNoneSkipLast = 5 kCGImageAlphaNoneSkipFirst = 6 kCGImageAlphaOnly = 7 # Tablet kEventTabletPoint = 1 kEventTabletProximity = 2 kEventParamTabletPointRec = _name('tbrc') kEventParamTabletProximityRec = _name('tbpx') typeTabletPointRec = _name('tbrc') typeTabletProximityRec = _name('tbpx')
Python
import pyglet # Cocoa implementation: if pyglet.options['darwin_cocoa']: from cocoapy import * # Carbon implementation: else: from types import * from constants import * carbon = pyglet.lib.load_library( framework='/System/Library/Frameworks/Carbon.framework') # No 64-bit version of quicktime # (It was replaced with QTKit, which is written in Objective-C) quicktime = pyglet.lib.load_library( framework='/System/Library/Frameworks/QuickTime.framework') carbon.GetEventDispatcherTarget.restype = EventTargetRef carbon.ReceiveNextEvent.argtypes = \ [c_uint32, c_void_p, c_double, c_ubyte, POINTER(EventRef)] #carbon.GetWindowPort.restype = agl.AGLDrawable EventHandlerProcPtr = CFUNCTYPE(c_int, c_int, c_void_p, c_void_p) # CarbonEvent functions are not available in 64-bit Carbon carbon.NewEventHandlerUPP.restype = c_void_p carbon.GetCurrentKeyModifiers = c_uint32 carbon.NewRgn.restype = RgnHandle carbon.CGDisplayBounds.argtypes = [c_void_p] carbon.CGDisplayBounds.restype = CGRect def create_cfstring(text): return carbon.CFStringCreateWithCString(c_void_p(), text.encode('utf8'), kCFStringEncodingUTF8) def _oscheck(result): if result != noErr: raise RuntimeError('Carbon error %d' % result) return result
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from pyglet.window import key from constants import * keymap = { ord('A'): key.A, ord('B'): key.B, ord('C'): key.C, ord('D'): key.D, ord('E'): key.E, ord('F'): key.F, ord('G'): key.G, ord('H'): key.H, ord('I'): key.I, ord('J'): key.J, ord('K'): key.K, ord('L'): key.L, ord('M'): key.M, ord('N'): key.N, ord('O'): key.O, ord('P'): key.P, ord('Q'): key.Q, ord('R'): key.R, ord('S'): key.S, ord('T'): key.T, ord('U'): key.U, ord('V'): key.V, ord('W'): key.W, ord('X'): key.X, ord('Y'): key.Y, ord('Z'): key.Z, ord('0'): key._0, ord('1'): key._1, ord('2'): key._2, ord('3'): key._3, ord('4'): key._4, ord('5'): key._5, ord('6'): key._6, ord('7'): key._7, ord('8'): key._8, ord('9'): key._9, ord('\b'): key.BACKSPACE, # By experiment: 0x14: key.CAPSLOCK, 0x5d: key.MENU, # VK_LBUTTON: , # VK_RBUTTON: , VK_CANCEL: key.CANCEL, # VK_MBUTTON: , # VK_BACK: , VK_TAB: key.TAB, # VK_CLEAR: , VK_RETURN: key.RETURN, VK_SHIFT: key.LSHIFT, VK_CONTROL: key.LCTRL, VK_MENU: key.LALT, VK_PAUSE: key.PAUSE, # VK_CAPITAL: , # VK_KANA: , # VK_HANGEUL: , # VK_HANGUL: , # VK_JUNJA: , # VK_FINAL: , # VK_HANJA: , # VK_KANJI: , VK_ESCAPE: key.ESCAPE, # VK_CONVERT: , # VK_NONCONVERT: , # VK_ACCEPT: , # VK_MODECHANGE: , VK_SPACE: key.SPACE, VK_PRIOR: key.PAGEUP, VK_NEXT: key.PAGEDOWN, VK_END: key.END, VK_HOME: key.HOME, VK_LEFT: key.LEFT, VK_UP: key.UP, VK_RIGHT: key.RIGHT, VK_DOWN: key.DOWN, # VK_SELECT: , VK_PRINT: key.PRINT, # VK_EXECUTE: , # VK_SNAPSHOT: , VK_INSERT: key.INSERT, VK_DELETE: key.DELETE, VK_HELP: key.HELP, VK_LWIN: key.LWINDOWS, VK_RWIN: key.RWINDOWS, # VK_APPS: , VK_NUMPAD0: key.NUM_0, VK_NUMPAD1: key.NUM_1, VK_NUMPAD2: key.NUM_2, VK_NUMPAD3: key.NUM_3, VK_NUMPAD4: key.NUM_4, VK_NUMPAD5: key.NUM_5, VK_NUMPAD6: key.NUM_6, VK_NUMPAD7: key.NUM_7, VK_NUMPAD8: key.NUM_8, VK_NUMPAD9: key.NUM_9, VK_MULTIPLY: key.NUM_MULTIPLY, VK_ADD: key.NUM_ADD, # VK_SEPARATOR: , VK_SUBTRACT: key.NUM_SUBTRACT, VK_DECIMAL: key.NUM_DECIMAL, VK_DIVIDE: key.NUM_DIVIDE, VK_F1: key.F1, VK_F2: key.F2, VK_F3: key.F3, VK_F4: key.F4, VK_F5: key.F5, VK_F6: key.F6, VK_F7: key.F7, VK_F8: key.F8, VK_F9: key.F9, VK_F10: key.F10, VK_F11: key.F11, VK_F12: key.F12, VK_F13: key.F13, VK_F14: key.F14, VK_F15: key.F15, VK_F16: key.F16, # VK_F17: , # VK_F18: , # VK_F19: , # VK_F20: , # VK_F21: , # VK_F22: , # VK_F23: , # VK_F24: , VK_NUMLOCK: key.NUMLOCK, VK_SCROLL: key.SCROLLLOCK, VK_LSHIFT: key.LSHIFT, VK_RSHIFT: key.RSHIFT, VK_LCONTROL: key.LCTRL, VK_RCONTROL: key.RCTRL, VK_LMENU: key.LALT, VK_RMENU: key.RALT, # VK_PROCESSKEY: , # VK_ATTN: , # VK_CRSEL: , # VK_EXSEL: , # VK_EREOF: , # VK_PLAY: , # VK_ZOOM: , # VK_NONAME: , # VK_PA1: , # VK_OEM_CLEAR: , # VK_XBUTTON1: , # VK_XBUTTON2: , # VK_VOLUME_MUTE: , # VK_VOLUME_DOWN: , # VK_VOLUME_UP: , # VK_MEDIA_NEXT_TRACK: , # VK_MEDIA_PREV_TRACK: , # VK_MEDIA_PLAY_PAUSE: , # VK_BROWSER_BACK: , # VK_BROWSER_FORWARD: , } # Keys that must be translated via MapVirtualKey, as the virtual key code # is language and keyboard dependent. chmap = { ord('!'): key.EXCLAMATION, ord('"'): key.DOUBLEQUOTE, ord('#'): key.HASH, ord('$'): key.DOLLAR, ord('%'): key.PERCENT, ord('&'): key.AMPERSAND, ord("'"): key.APOSTROPHE, ord('('): key.PARENLEFT, ord(')'): key.PARENRIGHT, ord('*'): key.ASTERISK, ord('+'): key.PLUS, ord(','): key.COMMA, ord('-'): key.MINUS, ord('.'): key.PERIOD, ord('/'): key.SLASH, ord(':'): key.COLON, ord(';'): key.SEMICOLON, ord('<'): key.LESS, ord('='): key.EQUAL, ord('>'): key.GREATER, ord('?'): key.QUESTION, ord('@'): key.AT, ord('['): key.BRACKETLEFT, ord('\\'): key.BACKSLASH, ord(']'): key.BRACKETRIGHT, ord('\x5e'): key.ASCIICIRCUM, ord('_'): key.UNDERSCORE, ord('\x60'): key.GRAVE, ord('`'): key.QUOTELEFT, ord('{'): key.BRACELEFT, ord('|'): key.BAR, ord('}'): key.BRACERIGHT, ord('~'): key.ASCIITILDE, }
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from ctypes import * from ctypes.wintypes import * INT = c_int LPVOID = c_void_p HCURSOR = HANDLE LRESULT = LPARAM COLORREF = DWORD PVOID = c_void_p WCHAR = c_wchar BCHAR = c_wchar LPRECT = POINTER(RECT) LPPOINT = POINTER(POINT) LPMSG = POINTER(MSG) UINT_PTR = HANDLE LONG_PTR = HANDLE LF_FACESIZE = 32 CCHDEVICENAME = 32 CCHFORMNAME = 32 WNDPROC = WINFUNCTYPE(LRESULT, HWND, UINT, WPARAM, LPARAM) TIMERPROC = WINFUNCTYPE(None, HWND, UINT, POINTER(UINT), DWORD) TIMERAPCPROC = WINFUNCTYPE(None, PVOID, DWORD, DWORD) MONITORENUMPROC = WINFUNCTYPE(BOOL, HMONITOR, HDC, LPRECT, LPARAM) def MAKEINTRESOURCE(i): return cast(c_void_p(i&0xFFFF), c_wchar_p) class WNDCLASS(Structure): _fields_ = [ ('style', UINT), ('lpfnWndProc', WNDPROC), ('cbClsExtra', c_int), ('cbWndExtra', c_int), ('hInstance', HINSTANCE), ('hIcon', HICON), ('hCursor', HCURSOR), ('hbrBackground', HBRUSH), ('lpszMenuName', c_char_p), ('lpszClassName', c_wchar_p) ] class SECURITY_ATTRIBUTES(Structure): _fields_ = [ ("nLength", DWORD), ("lpSecurityDescriptor", c_void_p), ("bInheritHandle", BOOL) ] __slots__ = [f[0] for f in _fields_] class PIXELFORMATDESCRIPTOR(Structure): _fields_ = [ ('nSize', WORD), ('nVersion', WORD), ('dwFlags', DWORD), ('iPixelType', BYTE), ('cColorBits', BYTE), ('cRedBits', BYTE), ('cRedShift', BYTE), ('cGreenBits', BYTE), ('cGreenShift', BYTE), ('cBlueBits', BYTE), ('cBlueShift', BYTE), ('cAlphaBits', BYTE), ('cAlphaShift', BYTE), ('cAccumBits', BYTE), ('cAccumRedBits', BYTE), ('cAccumGreenBits', BYTE), ('cAccumBlueBits', BYTE), ('cAccumAlphaBits', BYTE), ('cDepthBits', BYTE), ('cStencilBits', BYTE), ('cAuxBuffers', BYTE), ('iLayerType', BYTE), ('bReserved', BYTE), ('dwLayerMask', DWORD), ('dwVisibleMask', DWORD), ('dwDamageMask', DWORD) ] class RGBQUAD(Structure): _fields_ = [ ('rgbBlue', BYTE), ('rgbGreen', BYTE), ('rgbRed', BYTE), ('rgbReserved', BYTE), ] __slots__ = [f[0] for f in _fields_] class CIEXYZ(Structure): _fields_ = [ ('ciexyzX', DWORD), ('ciexyzY', DWORD), ('ciexyzZ', DWORD), ] __slots__ = [f[0] for f in _fields_] class CIEXYZTRIPLE(Structure): _fields_ = [ ('ciexyzRed', CIEXYZ), ('ciexyzBlue', CIEXYZ), ('ciexyzGreen', CIEXYZ), ] __slots__ = [f[0] for f in _fields_] class BITMAPINFOHEADER(Structure): _fields_ = [ ('biSize', DWORD), ('biWidth', LONG), ('biHeight', LONG), ('biPlanes', WORD), ('biBitCount', WORD), ('biCompression', DWORD), ('biSizeImage', DWORD), ('biXPelsPerMeter', LONG), ('biYPelsPerMeter', LONG), ('biClrUsed', DWORD), ('biClrImportant', DWORD), ] class BITMAPV5HEADER(Structure): _fields_ = [ ('bV5Size', DWORD), ('bV5Width', LONG), ('bV5Height', LONG), ('bV5Planes', WORD), ('bV5BitCount', WORD), ('bV5Compression', DWORD), ('bV5SizeImage', DWORD), ('bV5XPelsPerMeter', LONG), ('bV5YPelsPerMeter', LONG), ('bV5ClrUsed', DWORD), ('bV5ClrImportant', DWORD), ('bV5RedMask', DWORD), ('bV5GreenMask', DWORD), ('bV5BlueMask', DWORD), ('bV5AlphaMask', DWORD), ('bV5CSType', DWORD), ('bV5Endpoints', CIEXYZTRIPLE), ('bV5GammaRed', DWORD), ('bV5GammaGreen', DWORD), ('bV5GammaBlue', DWORD), ('bV5Intent', DWORD), ('bV5ProfileData', DWORD), ('bV5ProfileSize', DWORD), ('bV5Reserved', DWORD), ] class BITMAPINFO(Structure): _fields_ = [ ('bmiHeader', BITMAPINFOHEADER), ('bmiColors', RGBQUAD * 1) ] __slots__ = [f[0] for f in _fields_] class LOGFONT(Structure): _fields_ = [ ('lfHeight', LONG), ('lfWidth', LONG), ('lfEscapement', LONG), ('lfOrientation', LONG), ('lfWeight', LONG), ('lfItalic', BYTE), ('lfUnderline', BYTE), ('lfStrikeOut', BYTE), ('lfCharSet', BYTE), ('lfOutPrecision', BYTE), ('lfClipPrecision', BYTE), ('lfQuality', BYTE), ('lfPitchAndFamily', BYTE), ('lfFaceName', (c_char * LF_FACESIZE)) # Use ASCII ] class TRACKMOUSEEVENT(Structure): _fields_ = [ ('cbSize', DWORD), ('dwFlags', DWORD), ('hwndTrack', HWND), ('dwHoverTime', DWORD) ] __slots__ = [f[0] for f in _fields_] class MINMAXINFO(Structure): _fields_ = [ ('ptReserved', POINT), ('ptMaxSize', POINT), ('ptMaxPosition', POINT), ('ptMinTrackSize', POINT), ('ptMaxTrackSize', POINT) ] __slots__ = [f[0] for f in _fields_] class ABC(Structure): _fields_ = [ ('abcA', c_int), ('abcB', c_uint), ('abcC', c_int) ] __slots__ = [f[0] for f in _fields_] class TEXTMETRIC(Structure): _fields_ = [ ('tmHeight', c_long), ('tmAscent', c_long), ('tmDescent', c_long), ('tmInternalLeading', c_long), ('tmExternalLeading', c_long), ('tmAveCharWidth', c_long), ('tmMaxCharWidth', c_long), ('tmWeight', c_long), ('tmOverhang', c_long), ('tmDigitizedAspectX', c_long), ('tmDigitizedAspectY', c_long), ('tmFirstChar', c_char), # Use ASCII ('tmLastChar', c_char), ('tmDefaultChar', c_char), ('tmBreakChar', c_char), ('tmItalic', c_byte), ('tmUnderlined', c_byte), ('tmStruckOut', c_byte), ('tmPitchAndFamily', c_byte), ('tmCharSet', c_byte) ] __slots__ = [f[0] for f in _fields_] class MONITORINFOEX(Structure): _fields_ = [ ('cbSize', DWORD), ('rcMonitor', RECT), ('rcWork', RECT), ('dwFlags', DWORD), ('szDevice', WCHAR * CCHDEVICENAME) ] __slots__ = [f[0] for f in _fields_] class DEVMODE(Structure): _fields_ = [ ('dmDeviceName', BCHAR * CCHDEVICENAME), ('dmSpecVersion', WORD), ('dmDriverVersion', WORD), ('dmSize', WORD), ('dmDriverExtra', WORD), ('dmFields', DWORD), # Just using largest union member here ('dmOrientation', c_short), ('dmPaperSize', c_short), ('dmPaperLength', c_short), ('dmPaperWidth', c_short), ('dmScale', c_short), ('dmCopies', c_short), ('dmDefaultSource', c_short), ('dmPrintQuality', c_short), # End union ('dmColor', c_short), ('dmDuplex', c_short), ('dmYResolution', c_short), ('dmTTOption', c_short), ('dmCollate', c_short), ('dmFormName', BCHAR * CCHFORMNAME), ('dmLogPixels', WORD), ('dmBitsPerPel', DWORD), ('dmPelsWidth', DWORD), ('dmPelsHeight', DWORD), ('dmDisplayFlags', DWORD), # union with dmNup ('dmDisplayFrequency', DWORD), ('dmICMMethod', DWORD), ('dmICMIntent', DWORD), ('dmDitherType', DWORD), ('dmReserved1', DWORD), ('dmReserved2', DWORD), ('dmPanningWidth', DWORD), ('dmPanningHeight', DWORD), ] class ICONINFO(Structure): _fields_ = [ ('fIcon', BOOL), ('xHotspot', DWORD), ('yHotspot', DWORD), ('hbmMask', HBITMAP), ('hbmColor', HBITMAP) ] __slots__ = [f[0] for f in _fields_]
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # Most of this file is win32con.py from Python for Windows Extensions: # http://www.python.net/crew/mhammond/win32/ # From Windows 2000 API SuperBible: VK_OEM_1 = 0xba VK_OEM_PLUS = 0xbb VK_OEM_COMMA = 0xbc VK_OEM_MINUS = 0xbd VK_OEM_PERIOD = 0xbe VK_OEM_2 = 0xbf VK_OEM_3 = 0xc0 VK_OEM_4 = 0xdb VK_OEM_5 = 0xdc VK_OEM_6 = 0xdd VK_OEM_7 = 0xde VK_OEM_8 = 0xdf VK_OEM_102 = 0xe2 # Copyright (c) 1994-2001, Mark Hammond # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the distribution. # # Neither name of Mark Hammond nor the name of contributors may be used # to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS # IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. P # From WinGDI.h PFD_TYPE_RGBA = 0 PFD_TYPE_COLORINDEX = 1 PFD_MAIN_PLANE = 0 PFD_OVERLAY_PLANE = 1 PFD_UNDERLAY_PLANE = (-1) PFD_DOUBLEBUFFER = 0x00000001 PFD_STEREO = 0x00000002 PFD_DRAW_TO_WINDOW = 0x00000004 PFD_DRAW_TO_BITMAP = 0x00000008 PFD_SUPPORT_GDI = 0x00000010 PFD_SUPPORT_OPENGL = 0x00000020 PFD_GENERIC_FORMAT = 0x00000040 PFD_NEED_PALETTE = 0x00000080 PFD_NEED_SYSTEM_PALETTE = 0x00000100 PFD_SWAP_EXCHANGE = 0x00000200 PFD_SWAP_COPY = 0x00000400 PFD_SWAP_LAYER_BUFFERS = 0x00000800 PFD_GENERIC_ACCELERATED = 0x00001000 PFD_SUPPORT_DIRECTDRAW = 0x00002000 PFD_DEPTH_DONTCARE = 0x20000000 PFD_DOUBLEBUFFER_DONTCARE = 0x40000000 PFD_STEREO_DONTCARE = 0x80000000 # Generated by h2py from commdlg.h (plus modifications 4jan98) WINVER = 1280 WM_USER = 1024 PY_0U = 0 OFN_READONLY = 1 OFN_OVERWRITEPROMPT = 2 OFN_HIDEREADONLY = 4 OFN_NOCHANGEDIR = 8 OFN_SHOWHELP = 16 OFN_ENABLEHOOK = 32 OFN_ENABLETEMPLATE = 64 OFN_ENABLETEMPLATEHANDLE = 128 OFN_NOVALIDATE = 256 OFN_ALLOWMULTISELECT = 512 OFN_EXTENSIONDIFFERENT = 1024 OFN_PATHMUSTEXIST = 2048 OFN_FILEMUSTEXIST = 4096 OFN_CREATEPROMPT = 8192 OFN_SHAREAWARE = 16384 OFN_NOREADONLYRETURN = 32768 OFN_NOTESTFILECREATE = 65536 OFN_NONETWORKBUTTON = 131072 OFN_NOLONGNAMES = 262144 OFN_EXPLORER = 524288 # new look commdlg OFN_NODEREFERENCELINKS = 1048576 OFN_LONGNAMES = 2097152 # force long names for 3.x modules OFN_ENABLEINCLUDENOTIFY = 4194304 # send include message to callback OFN_ENABLESIZING = 8388608 OFN_DONTADDTORECENT = 33554432 OFN_FORCESHOWHIDDEN = 268435456 # Show All files including System and hidden files OFN_EX_NOPLACESBAR = 1 OFN_SHAREFALLTHROUGH = 2 OFN_SHARENOWARN = 1 OFN_SHAREWARN = 0 CDN_FIRST = (PY_0U-601) CDN_LAST = (PY_0U-699) CDN_INITDONE = (CDN_FIRST - 0) CDN_SELCHANGE = (CDN_FIRST - 1) CDN_FOLDERCHANGE = (CDN_FIRST - 2) CDN_SHAREVIOLATION = (CDN_FIRST - 3) CDN_HELP = (CDN_FIRST - 4) CDN_FILEOK = (CDN_FIRST - 5) CDN_TYPECHANGE = (CDN_FIRST - 6) CDN_INCLUDEITEM = (CDN_FIRST - 7) CDM_FIRST = (WM_USER + 100) CDM_LAST = (WM_USER + 200) CDM_GETSPEC = (CDM_FIRST + 0) CDM_GETFILEPATH = (CDM_FIRST + 1) CDM_GETFOLDERPATH = (CDM_FIRST + 2) CDM_GETFOLDERIDLIST = (CDM_FIRST + 3) CDM_SETCONTROLTEXT = (CDM_FIRST + 4) CDM_HIDECONTROL = (CDM_FIRST + 5) CDM_SETDEFEXT = (CDM_FIRST + 6) CC_RGBINIT = 1 CC_FULLOPEN = 2 CC_PREVENTFULLOPEN = 4 CC_SHOWHELP = 8 CC_ENABLEHOOK = 16 CC_ENABLETEMPLATE = 32 CC_ENABLETEMPLATEHANDLE = 64 CC_SOLIDCOLOR = 128 CC_ANYCOLOR = 256 FR_DOWN = 1 FR_WHOLEWORD = 2 FR_MATCHCASE = 4 FR_FINDNEXT = 8 FR_REPLACE = 16 FR_REPLACEALL = 32 FR_DIALOGTERM = 64 FR_SHOWHELP = 128 FR_ENABLEHOOK = 256 FR_ENABLETEMPLATE = 512 FR_NOUPDOWN = 1024 FR_NOMATCHCASE = 2048 FR_NOWHOLEWORD = 4096 FR_ENABLETEMPLATEHANDLE = 8192 FR_HIDEUPDOWN = 16384 FR_HIDEMATCHCASE = 32768 FR_HIDEWHOLEWORD = 65536 CF_SCREENFONTS = 1 CF_PRINTERFONTS = 2 CF_BOTH = (CF_SCREENFONTS | CF_PRINTERFONTS) CF_SHOWHELP = 4 CF_ENABLEHOOK = 8 CF_ENABLETEMPLATE = 16 CF_ENABLETEMPLATEHANDLE = 32 CF_INITTOLOGFONTSTRUCT = 64 CF_USESTYLE = 128 CF_EFFECTS = 256 CF_APPLY = 512 CF_ANSIONLY = 1024 CF_SCRIPTSONLY = CF_ANSIONLY CF_NOVECTORFONTS = 2048 CF_NOOEMFONTS = CF_NOVECTORFONTS CF_NOSIMULATIONS = 4096 CF_LIMITSIZE = 8192 CF_FIXEDPITCHONLY = 16384 CF_WYSIWYG = 32768 # must also have CF_SCREENFONTS & CF_PRINTERFONTS CF_FORCEFONTEXIST = 65536 CF_SCALABLEONLY = 131072 CF_TTONLY = 262144 CF_NOFACESEL = 524288 CF_NOSTYLESEL = 1048576 CF_NOSIZESEL = 2097152 CF_SELECTSCRIPT = 4194304 CF_NOSCRIPTSEL = 8388608 CF_NOVERTFONTS = 16777216 SIMULATED_FONTTYPE = 32768 PRINTER_FONTTYPE = 16384 SCREEN_FONTTYPE = 8192 BOLD_FONTTYPE = 256 ITALIC_FONTTYPE = 512 REGULAR_FONTTYPE = 1024 OPENTYPE_FONTTYPE = 65536 TYPE1_FONTTYPE = 131072 DSIG_FONTTYPE = 262144 WM_CHOOSEFONT_GETLOGFONT = (WM_USER + 1) WM_CHOOSEFONT_SETLOGFONT = (WM_USER + 101) WM_CHOOSEFONT_SETFLAGS = (WM_USER + 102) LBSELCHSTRINGA = "commdlg_LBSelChangedNotify" SHAREVISTRINGA = "commdlg_ShareViolation" FILEOKSTRINGA = "commdlg_FileNameOK" COLOROKSTRINGA = "commdlg_ColorOK" SETRGBSTRINGA = "commdlg_SetRGBColor" HELPMSGSTRINGA = "commdlg_help" FINDMSGSTRINGA = "commdlg_FindReplace" LBSELCHSTRING = LBSELCHSTRINGA SHAREVISTRING = SHAREVISTRINGA FILEOKSTRING = FILEOKSTRINGA COLOROKSTRING = COLOROKSTRINGA SETRGBSTRING = SETRGBSTRINGA HELPMSGSTRING = HELPMSGSTRINGA FINDMSGSTRING = FINDMSGSTRINGA CD_LBSELNOITEMS = -1 CD_LBSELCHANGE = 0 CD_LBSELSUB = 1 CD_LBSELADD = 2 PD_ALLPAGES = 0 PD_SELECTION = 1 PD_PAGENUMS = 2 PD_NOSELECTION = 4 PD_NOPAGENUMS = 8 PD_COLLATE = 16 PD_PRINTTOFILE = 32 PD_PRINTSETUP = 64 PD_NOWARNING = 128 PD_RETURNDC = 256 PD_RETURNIC = 512 PD_RETURNDEFAULT = 1024 PD_SHOWHELP = 2048 PD_ENABLEPRINTHOOK = 4096 PD_ENABLESETUPHOOK = 8192 PD_ENABLEPRINTTEMPLATE = 16384 PD_ENABLESETUPTEMPLATE = 32768 PD_ENABLEPRINTTEMPLATEHANDLE = 65536 PD_ENABLESETUPTEMPLATEHANDLE = 131072 PD_USEDEVMODECOPIES = 262144 PD_DISABLEPRINTTOFILE = 524288 PD_HIDEPRINTTOFILE = 1048576 PD_NONETWORKBUTTON = 2097152 DN_DEFAULTPRN = 1 WM_PSD_PAGESETUPDLG = (WM_USER ) WM_PSD_FULLPAGERECT = (WM_USER+1) WM_PSD_MINMARGINRECT = (WM_USER+2) WM_PSD_MARGINRECT = (WM_USER+3) WM_PSD_GREEKTEXTRECT = (WM_USER+4) WM_PSD_ENVSTAMPRECT = (WM_USER+5) WM_PSD_YAFULLPAGERECT = (WM_USER+6) PSD_DEFAULTMINMARGINS = 0 # default (printer's) PSD_INWININIINTLMEASURE = 0 # 1st of 4 possible PSD_MINMARGINS = 1 # use caller's PSD_MARGINS = 2 # use caller's PSD_INTHOUSANDTHSOFINCHES = 4 # 2nd of 4 possible PSD_INHUNDREDTHSOFMILLIMETERS = 8 # 3rd of 4 possible PSD_DISABLEMARGINS = 16 PSD_DISABLEPRINTER = 32 PSD_NOWARNING = 128 # must be same as PD_* PSD_DISABLEORIENTATION = 256 PSD_RETURNDEFAULT = 1024 # must be same as PD_* PSD_DISABLEPAPER = 512 PSD_SHOWHELP = 2048 # must be same as PD_* PSD_ENABLEPAGESETUPHOOK = 8192 # must be same as PD_* PSD_ENABLEPAGESETUPTEMPLATE = 32768 # must be same as PD_* PSD_ENABLEPAGESETUPTEMPLATEHANDLE = 131072 # must be same as PD_* PSD_ENABLEPAGEPAINTHOOK = 262144 PSD_DISABLEPAGEPAINTING = 524288 PSD_NONETWORKBUTTON = 2097152 # must be same as PD_* # Generated by h2py from winreg.h HKEY_CLASSES_ROOT = -2147483648 HKEY_CURRENT_USER = -2147483647 HKEY_LOCAL_MACHINE = -2147483646 HKEY_USERS = -2147483645 HKEY_PERFORMANCE_DATA = -2147483644 HKEY_CURRENT_CONFIG = -2147483643 HKEY_DYN_DATA = -2147483642 HKEY_PERFORMANCE_TEXT = -2147483568 # ?? 4Jan98 HKEY_PERFORMANCE_NLSTEXT = -2147483552 # ?? 4Jan98 # Generated by h2py from winuser.h HWND_BROADCAST = 65535 HWND_DESKTOP = 0 HWND_TOP = 0 HWND_BOTTOM = 1 HWND_TOPMOST = -1 HWND_NOTOPMOST = -2 HWND_MESSAGE = -3 # winuser.h line 4601 SM_CXSCREEN = 0 SM_CYSCREEN = 1 SM_CXVSCROLL = 2 SM_CYHSCROLL = 3 SM_CYCAPTION = 4 SM_CXBORDER = 5 SM_CYBORDER = 6 SM_CXDLGFRAME = 7 SM_CYDLGFRAME = 8 SM_CYVTHUMB = 9 SM_CXHTHUMB = 10 SM_CXICON = 11 SM_CYICON = 12 SM_CXCURSOR = 13 SM_CYCURSOR = 14 SM_CYMENU = 15 SM_CXFULLSCREEN = 16 SM_CYFULLSCREEN = 17 SM_CYKANJIWINDOW = 18 SM_MOUSEPRESENT = 19 SM_CYVSCROLL = 20 SM_CXHSCROLL = 21 SM_DEBUG = 22 SM_SWAPBUTTON = 23 SM_RESERVED1 = 24 SM_RESERVED2 = 25 SM_RESERVED3 = 26 SM_RESERVED4 = 27 SM_CXMIN = 28 SM_CYMIN = 29 SM_CXSIZE = 30 SM_CYSIZE = 31 SM_CXFRAME = 32 SM_CYFRAME = 33 SM_CXMINTRACK = 34 SM_CYMINTRACK = 35 SM_CXDOUBLECLK = 36 SM_CYDOUBLECLK = 37 SM_CXICONSPACING = 38 SM_CYICONSPACING = 39 SM_MENUDROPALIGNMENT = 40 SM_PENWINDOWS = 41 SM_DBCSENABLED = 42 SM_CMOUSEBUTTONS = 43 SM_CXFIXEDFRAME = SM_CXDLGFRAME SM_CYFIXEDFRAME = SM_CYDLGFRAME SM_CXSIZEFRAME = SM_CXFRAME SM_CYSIZEFRAME = SM_CYFRAME SM_SECURE = 44 SM_CXEDGE = 45 SM_CYEDGE = 46 SM_CXMINSPACING = 47 SM_CYMINSPACING = 48 SM_CXSMICON = 49 SM_CYSMICON = 50 SM_CYSMCAPTION = 51 SM_CXSMSIZE = 52 SM_CYSMSIZE = 53 SM_CXMENUSIZE = 54 SM_CYMENUSIZE = 55 SM_ARRANGE = 56 SM_CXMINIMIZED = 57 SM_CYMINIMIZED = 58 SM_CXMAXTRACK = 59 SM_CYMAXTRACK = 60 SM_CXMAXIMIZED = 61 SM_CYMAXIMIZED = 62 SM_NETWORK = 63 SM_CLEANBOOT = 67 SM_CXDRAG = 68 SM_CYDRAG = 69 SM_SHOWSOUNDS = 70 SM_CXMENUCHECK = 71 SM_CYMENUCHECK = 72 SM_SLOWMACHINE = 73 SM_MIDEASTENABLED = 74 SM_MOUSEWHEELPRESENT = 75 SM_XVIRTUALSCREEN = 76 SM_YVIRTUALSCREEN = 77 SM_CXVIRTUALSCREEN = 78 SM_CYVIRTUALSCREEN = 79 SM_CMONITORS = 80 SM_SAMEDISPLAYFORMAT = 81 SM_CMETRICS = 83 MNC_IGNORE = 0 MNC_CLOSE = 1 MNC_EXECUTE = 2 MNC_SELECT = 3 MNS_NOCHECK = -2147483648 MNS_MODELESS = 1073741824 MNS_DRAGDROP = 536870912 MNS_AUTODISMISS = 268435456 MNS_NOTIFYBYPOS = 134217728 MNS_CHECKORBMP = 67108864 MIM_MAXHEIGHT = 1 MIM_BACKGROUND = 2 MIM_HELPID = 4 MIM_MENUDATA = 8 MIM_STYLE = 16 MIM_APPLYTOSUBMENUS = -2147483648 MND_CONTINUE = 0 MND_ENDMENU = 1 MNGOF_GAP = 3 MNGO_NOINTERFACE = 0 MNGO_NOERROR = 1 MIIM_STATE = 1 MIIM_ID = 2 MIIM_SUBMENU = 4 MIIM_CHECKMARKS = 8 MIIM_TYPE = 16 MIIM_DATA = 32 MIIM_STRING = 64 MIIM_BITMAP = 128 MIIM_FTYPE = 256 HBMMENU_CALLBACK = -1 HBMMENU_SYSTEM = 1 HBMMENU_MBAR_RESTORE = 2 HBMMENU_MBAR_MINIMIZE = 3 HBMMENU_MBAR_CLOSE = 5 HBMMENU_MBAR_CLOSE_D = 6 HBMMENU_MBAR_MINIMIZE_D = 7 HBMMENU_POPUP_CLOSE = 8 HBMMENU_POPUP_RESTORE = 9 HBMMENU_POPUP_MAXIMIZE = 10 HBMMENU_POPUP_MINIMIZE = 11 GMDI_USEDISABLED = 1 GMDI_GOINTOPOPUPS = 2 TPM_LEFTBUTTON = 0 TPM_RIGHTBUTTON = 2 TPM_LEFTALIGN = 0 TPM_CENTERALIGN = 4 TPM_RIGHTALIGN = 8 TPM_TOPALIGN = 0 TPM_VCENTERALIGN = 16 TPM_BOTTOMALIGN = 32 TPM_HORIZONTAL = 0 TPM_VERTICAL = 64 TPM_NONOTIFY = 128 TPM_RETURNCMD = 256 TPM_RECURSE = 1 DOF_EXECUTABLE = 32769 DOF_DOCUMENT = 32770 DOF_DIRECTORY = 32771 DOF_MULTIPLE = 32772 DOF_PROGMAN = 1 DOF_SHELLDATA = 2 DO_DROPFILE = 1162627398 DO_PRINTFILE = 1414419024 DT_TOP = 0 DT_LEFT = 0 DT_CENTER = 1 DT_RIGHT = 2 DT_VCENTER = 4 DT_BOTTOM = 8 DT_WORDBREAK = 16 DT_SINGLELINE = 32 DT_EXPANDTABS = 64 DT_TABSTOP = 128 DT_NOCLIP = 256 DT_EXTERNALLEADING = 512 DT_CALCRECT = 1024 DT_NOPREFIX = 2048 DT_INTERNAL = 4096 DT_EDITCONTROL = 8192 DT_PATH_ELLIPSIS = 16384 DT_END_ELLIPSIS = 32768 DT_MODIFYSTRING = 65536 DT_RTLREADING = 131072 DT_WORD_ELLIPSIS = 262144 DST_COMPLEX = 0 DST_TEXT = 1 DST_PREFIXTEXT = 2 DST_ICON = 3 DST_BITMAP = 4 DSS_NORMAL = 0 DSS_UNION = 16 DSS_DISABLED = 32 DSS_MONO = 128 DSS_RIGHT = 32768 DCX_WINDOW = 1 DCX_CACHE = 2 DCX_NORESETATTRS = 4 DCX_CLIPCHILDREN = 8 DCX_CLIPSIBLINGS = 16 DCX_PARENTCLIP = 32 DCX_EXCLUDERGN = 64 DCX_INTERSECTRGN = 128 DCX_EXCLUDEUPDATE = 256 DCX_INTERSECTUPDATE = 512 DCX_LOCKWINDOWUPDATE = 1024 DCX_VALIDATE = 2097152 CUDR_NORMAL = 0 CUDR_NOSNAPTOGRID = 1 CUDR_NORESOLVEPOSITIONS = 2 CUDR_NOCLOSEGAPS = 4 CUDR_NEGATIVECOORDS = 8 CUDR_NOPRIMARY = 16 RDW_INVALIDATE = 1 RDW_INTERNALPAINT = 2 RDW_ERASE = 4 RDW_VALIDATE = 8 RDW_NOINTERNALPAINT = 16 RDW_NOERASE = 32 RDW_NOCHILDREN = 64 RDW_ALLCHILDREN = 128 RDW_UPDATENOW = 256 RDW_ERASENOW = 512 RDW_FRAME = 1024 RDW_NOFRAME = 2048 SW_SCROLLCHILDREN = 1 SW_INVALIDATE = 2 SW_ERASE = 4 SW_SMOOTHSCROLL = 16 # Use smooth scrolling ESB_ENABLE_BOTH = 0 ESB_DISABLE_BOTH = 3 ESB_DISABLE_LEFT = 1 ESB_DISABLE_RIGHT = 2 ESB_DISABLE_UP = 1 ESB_DISABLE_DOWN = 2 ESB_DISABLE_LTUP = ESB_DISABLE_LEFT ESB_DISABLE_RTDN = ESB_DISABLE_RIGHT HELPINFO_WINDOW = 1 HELPINFO_MENUITEM = 2 MB_OK = 0 MB_OKCANCEL = 1 MB_ABORTRETRYIGNORE = 2 MB_YESNOCANCEL = 3 MB_YESNO = 4 MB_RETRYCANCEL = 5 MB_ICONHAND = 16 MB_ICONQUESTION = 32 MB_ICONEXCLAMATION = 48 MB_ICONASTERISK = 64 MB_ICONWARNING = MB_ICONEXCLAMATION MB_ICONERROR = MB_ICONHAND MB_ICONINFORMATION = MB_ICONASTERISK MB_ICONSTOP = MB_ICONHAND MB_DEFBUTTON1 = 0 MB_DEFBUTTON2 = 256 MB_DEFBUTTON3 = 512 MB_DEFBUTTON4 = 768 MB_APPLMODAL = 0 MB_SYSTEMMODAL = 4096 MB_TASKMODAL = 8192 MB_HELP = 16384 MB_NOFOCUS = 32768 MB_SETFOREGROUND = 65536 MB_DEFAULT_DESKTOP_ONLY = 131072 MB_TOPMOST = 262144L MB_RIGHT = 524288 MB_RTLREADING = 1048576 MB_SERVICE_NOTIFICATION = 2097152 MB_TYPEMASK = 15 MB_USERICON = 128 MB_ICONMASK = 240 MB_DEFMASK = 3840 MB_MODEMASK = 12288 MB_MISCMASK = 49152 # winuser.h line 6373 CWP_ALL = 0 CWP_SKIPINVISIBLE = 1 CWP_SKIPDISABLED = 2 CWP_SKIPTRANSPARENT = 4 CTLCOLOR_MSGBOX = 0 CTLCOLOR_EDIT = 1 CTLCOLOR_LISTBOX = 2 CTLCOLOR_BTN = 3 CTLCOLOR_DLG = 4 CTLCOLOR_SCROLLBAR = 5 CTLCOLOR_STATIC = 6 CTLCOLOR_MAX = 7 COLOR_SCROLLBAR = 0 COLOR_BACKGROUND = 1 COLOR_ACTIVECAPTION = 2 COLOR_INACTIVECAPTION = 3 COLOR_MENU = 4 COLOR_WINDOW = 5 COLOR_WINDOWFRAME = 6 COLOR_MENUTEXT = 7 COLOR_WINDOWTEXT = 8 COLOR_CAPTIONTEXT = 9 COLOR_ACTIVEBORDER = 10 COLOR_INACTIVEBORDER = 11 COLOR_APPWORKSPACE = 12 COLOR_HIGHLIGHT = 13 COLOR_HIGHLIGHTTEXT = 14 COLOR_BTNFACE = 15 COLOR_BTNSHADOW = 16 COLOR_GRAYTEXT = 17 COLOR_BTNTEXT = 18 COLOR_INACTIVECAPTIONTEXT = 19 COLOR_BTNHIGHLIGHT = 20 COLOR_3DDKSHADOW = 21 COLOR_3DLIGHT = 22 COLOR_INFOTEXT = 23 COLOR_INFOBK = 24 COLOR_HOTLIGHT = 26 COLOR_GRADIENTACTIVECAPTION = 27 COLOR_GRADIENTINACTIVECAPTION = 28 COLOR_DESKTOP = COLOR_BACKGROUND COLOR_3DFACE = COLOR_BTNFACE COLOR_3DSHADOW = COLOR_BTNSHADOW COLOR_3DHIGHLIGHT = COLOR_BTNHIGHLIGHT COLOR_3DHILIGHT = COLOR_BTNHIGHLIGHT COLOR_BTNHILIGHT = COLOR_BTNHIGHLIGHT GW_HWNDFIRST = 0 GW_HWNDLAST = 1 GW_HWNDNEXT = 2 GW_HWNDPREV = 3 GW_OWNER = 4 GW_CHILD = 5 GW_ENABLEDPOPUP = 6 GW_MAX = 6 MF_INSERT = 0 MF_CHANGE = 128 MF_APPEND = 256 MF_DELETE = 512 MF_REMOVE = 4096 MF_BYCOMMAND = 0 MF_BYPOSITION = 1024 MF_SEPARATOR = 2048 MF_ENABLED = 0 MF_GRAYED = 1 MF_DISABLED = 2 MF_UNCHECKED = 0 MF_CHECKED = 8 MF_USECHECKBITMAPS = 512 MF_STRING = 0 MF_BITMAP = 4 MF_OWNERDRAW = 256 MF_POPUP = 16 MF_MENUBARBREAK = 32 MF_MENUBREAK = 64 MF_UNHILITE = 0 MF_HILITE = 128 MF_DEFAULT = 4096 MF_SYSMENU = 8192 MF_HELP = 16384 MF_RIGHTJUSTIFY = 16384 MF_MOUSESELECT = 32768 MF_END = 128 MFT_STRING = MF_STRING MFT_BITMAP = MF_BITMAP MFT_MENUBARBREAK = MF_MENUBARBREAK MFT_MENUBREAK = MF_MENUBREAK MFT_OWNERDRAW = MF_OWNERDRAW MFT_RADIOCHECK = 512 MFT_SEPARATOR = MF_SEPARATOR MFT_RIGHTORDER = 8192 MFT_RIGHTJUSTIFY = MF_RIGHTJUSTIFY MFS_GRAYED = 3 MFS_DISABLED = MFS_GRAYED MFS_CHECKED = MF_CHECKED MFS_HILITE = MF_HILITE MFS_ENABLED = MF_ENABLED MFS_UNCHECKED = MF_UNCHECKED MFS_UNHILITE = MF_UNHILITE MFS_DEFAULT = MF_DEFAULT MFS_MASK = 4235L MFS_HOTTRACKDRAWN = 268435456 MFS_CACHEDBMP = 536870912 MFS_BOTTOMGAPDROP = 1073741824 MFS_TOPGAPDROP = -2147483648 MFS_GAPDROP = -1073741824 SC_SIZE = 61440 SC_MOVE = 61456 SC_MINIMIZE = 61472 SC_MAXIMIZE = 61488 SC_NEXTWINDOW = 61504 SC_PREVWINDOW = 61520 SC_CLOSE = 61536 SC_VSCROLL = 61552 SC_HSCROLL = 61568 SC_MOUSEMENU = 61584 SC_KEYMENU = 61696 SC_ARRANGE = 61712 SC_RESTORE = 61728 SC_TASKLIST = 61744 SC_SCREENSAVE = 61760 SC_HOTKEY = 61776 SC_DEFAULT = 61792 SC_MONITORPOWER = 61808 SC_CONTEXTHELP = 61824 SC_SEPARATOR = 61455 SC_ICON = SC_MINIMIZE SC_ZOOM = SC_MAXIMIZE IDC_ARROW = 32512 IDC_IBEAM = 32513 IDC_WAIT = 32514 IDC_CROSS = 32515 IDC_UPARROW = 32516 IDC_SIZE = 32640 # OBSOLETE: use IDC_SIZEALL IDC_ICON = 32641 # OBSOLETE: use IDC_ARROW IDC_SIZENWSE = 32642 IDC_SIZENESW = 32643 IDC_SIZEWE = 32644 IDC_SIZENS = 32645 IDC_SIZEALL = 32646 IDC_NO = 32648 IDC_HAND = 32649 IDC_APPSTARTING = 32650 IDC_HELP = 32651 IMAGE_BITMAP = 0 IMAGE_ICON = 1 IMAGE_CURSOR = 2 IMAGE_ENHMETAFILE = 3 LR_DEFAULTCOLOR = 0 LR_MONOCHROME = 1 LR_COLOR = 2 LR_COPYRETURNORG = 4 LR_COPYDELETEORG = 8 LR_LOADFROMFILE = 16 LR_LOADTRANSPARENT = 32 LR_DEFAULTSIZE = 64 LR_LOADREALSIZE = 128 LR_LOADMAP3DCOLORS = 4096 LR_CREATEDIBSECTION = 8192 LR_COPYFROMRESOURCE = 16384 LR_SHARED = 32768 DI_MASK = 1 DI_IMAGE = 2 DI_NORMAL = 3 DI_COMPAT = 4 DI_DEFAULTSIZE = 8 RES_ICON = 1 RES_CURSOR = 2 OBM_CLOSE = 32754 OBM_UPARROW = 32753 OBM_DNARROW = 32752 OBM_RGARROW = 32751 OBM_LFARROW = 32750 OBM_REDUCE = 32749 OBM_ZOOM = 32748 OBM_RESTORE = 32747 OBM_REDUCED = 32746 OBM_ZOOMD = 32745 OBM_RESTORED = 32744 OBM_UPARROWD = 32743 OBM_DNARROWD = 32742 OBM_RGARROWD = 32741 OBM_LFARROWD = 32740 OBM_MNARROW = 32739 OBM_COMBO = 32738 OBM_UPARROWI = 32737 OBM_DNARROWI = 32736 OBM_RGARROWI = 32735 OBM_LFARROWI = 32734 OBM_OLD_CLOSE = 32767 OBM_SIZE = 32766 OBM_OLD_UPARROW = 32765 OBM_OLD_DNARROW = 32764 OBM_OLD_RGARROW = 32763 OBM_OLD_LFARROW = 32762 OBM_BTSIZE = 32761 OBM_CHECK = 32760 OBM_CHECKBOXES = 32759 OBM_BTNCORNERS = 32758 OBM_OLD_REDUCE = 32757 OBM_OLD_ZOOM = 32756 OBM_OLD_RESTORE = 32755 OCR_NORMAL = 32512 OCR_IBEAM = 32513 OCR_WAIT = 32514 OCR_CROSS = 32515 OCR_UP = 32516 OCR_SIZE = 32640 OCR_ICON = 32641 OCR_SIZENWSE = 32642 OCR_SIZENESW = 32643 OCR_SIZEWE = 32644 OCR_SIZENS = 32645 OCR_SIZEALL = 32646 OCR_ICOCUR = 32647 OCR_NO = 32648 OCR_HAND = 32649 OCR_APPSTARTING = 32650 # winuser.h line 7455 OIC_SAMPLE = 32512 OIC_HAND = 32513 OIC_QUES = 32514 OIC_BANG = 32515 OIC_NOTE = 32516 OIC_WINLOGO = 32517 OIC_WARNING = OIC_BANG OIC_ERROR = OIC_HAND OIC_INFORMATION = OIC_NOTE ORD_LANGDRIVER = 1 IDI_APPLICATION = 32512 IDI_HAND = 32513 IDI_QUESTION = 32514 IDI_EXCLAMATION = 32515 IDI_ASTERISK = 32516 IDI_WINLOGO = 32517 IDI_WARNING = IDI_EXCLAMATION IDI_ERROR = IDI_HAND IDI_INFORMATION = IDI_ASTERISK IDOK = 1 IDCANCEL = 2 IDABORT = 3 IDRETRY = 4 IDIGNORE = 5 IDYES = 6 IDNO = 7 IDCLOSE = 8 IDHELP = 9 ES_LEFT = 0 ES_CENTER = 1 ES_RIGHT = 2 ES_MULTILINE = 4 ES_UPPERCASE = 8 ES_LOWERCASE = 16 ES_PASSWORD = 32 ES_AUTOVSCROLL = 64 ES_AUTOHSCROLL = 128 ES_NOHIDESEL = 256 ES_OEMCONVERT = 1024 ES_READONLY = 2048 ES_WANTRETURN = 4096 ES_NUMBER = 8192 EN_SETFOCUS = 256 EN_KILLFOCUS = 512 EN_CHANGE = 768 EN_UPDATE = 1024 EN_ERRSPACE = 1280 EN_MAXTEXT = 1281 EN_HSCROLL = 1537 EN_VSCROLL = 1538 EC_LEFTMARGIN = 1 EC_RIGHTMARGIN = 2 EC_USEFONTINFO = 65535 EMSIS_COMPOSITIONSTRING = 1 EIMES_GETCOMPSTRATONCE = 1 EIMES_CANCELCOMPSTRINFOCUS = 2 EIMES_COMPLETECOMPSTRKILLFOCUS = 4 EM_GETSEL = 176 EM_SETSEL = 177 EM_GETRECT = 178 EM_SETRECT = 179 EM_SETRECTNP = 180 EM_SCROLL = 181 EM_LINESCROLL = 182 EM_SCROLLCARET = 183 EM_GETMODIFY = 184 EM_SETMODIFY = 185 EM_GETLINECOUNT = 186 EM_LINEINDEX = 187 EM_SETHANDLE = 188 EM_GETHANDLE = 189 EM_GETTHUMB = 190 EM_LINELENGTH = 193 EM_REPLACESEL = 194 EM_GETLINE = 196 EM_LIMITTEXT = 197 EM_CANUNDO = 198 EM_UNDO = 199 EM_FMTLINES = 200 EM_LINEFROMCHAR = 201 EM_SETTABSTOPS = 203 EM_SETPASSWORDCHAR = 204 EM_EMPTYUNDOBUFFER = 205 EM_GETFIRSTVISIBLELINE = 206 EM_SETREADONLY = 207 EM_SETWORDBREAKPROC = 208 EM_GETWORDBREAKPROC = 209 EM_GETPASSWORDCHAR = 210 EM_SETMARGINS = 211 EM_GETMARGINS = 212 EM_SETLIMITTEXT = EM_LIMITTEXT EM_GETLIMITTEXT = 213 EM_POSFROMCHAR = 214 EM_CHARFROMPOS = 215 EM_SETIMESTATUS = 216 EM_GETIMESTATUS = 217 WB_LEFT = 0 WB_RIGHT = 1 WB_ISDELIMITER = 2 BS_PUSHBUTTON = 0 BS_DEFPUSHBUTTON = 1 BS_CHECKBOX = 2 BS_AUTOCHECKBOX = 3 BS_RADIOBUTTON = 4 BS_3STATE = 5 BS_AUTO3STATE = 6 BS_GROUPBOX = 7 BS_USERBUTTON = 8 BS_AUTORADIOBUTTON = 9 BS_OWNERDRAW = 11L BS_LEFTTEXT = 32 BS_TEXT = 0 BS_ICON = 64 BS_BITMAP = 128 BS_LEFT = 256 BS_RIGHT = 512 BS_CENTER = 768 BS_TOP = 1024 BS_BOTTOM = 2048 BS_VCENTER = 3072 BS_PUSHLIKE = 4096 BS_MULTILINE = 8192 BS_NOTIFY = 16384 BS_FLAT = 32768 BS_RIGHTBUTTON = BS_LEFTTEXT BN_CLICKED = 0 BN_PAINT = 1 BN_HILITE = 2 BN_UNHILITE = 3 BN_DISABLE = 4 BN_DOUBLECLICKED = 5 BN_PUSHED = BN_HILITE BN_UNPUSHED = BN_UNHILITE BN_DBLCLK = BN_DOUBLECLICKED BN_SETFOCUS = 6 BN_KILLFOCUS = 7 BM_GETCHECK = 240 BM_SETCHECK = 241 BM_GETSTATE = 242 BM_SETSTATE = 243 BM_SETSTYLE = 244 BM_CLICK = 245 BM_GETIMAGE = 246 BM_SETIMAGE = 247 BST_UNCHECKED = 0 BST_CHECKED = 1 BST_INDETERMINATE = 2 BST_PUSHED = 4 BST_FOCUS = 8 SS_LEFT = 0 SS_CENTER = 1 SS_RIGHT = 2 SS_ICON = 3 SS_BLACKRECT = 4 SS_GRAYRECT = 5 SS_WHITERECT = 6 SS_BLACKFRAME = 7 SS_GRAYFRAME = 8 SS_WHITEFRAME = 9 SS_USERITEM = 10 SS_SIMPLE = 11 SS_LEFTNOWORDWRAP = 12 SS_BITMAP = 14 SS_OWNERDRAW = 13 SS_ENHMETAFILE = 15 SS_ETCHEDHORZ = 16 SS_ETCHEDVERT = 17 SS_ETCHEDFRAME = 18 SS_TYPEMASK = 31 SS_NOPREFIX = 128 SS_NOTIFY = 256 SS_CENTERIMAGE = 512 SS_RIGHTJUST = 1024 SS_REALSIZEIMAGE = 2048 SS_SUNKEN = 4096 SS_ENDELLIPSIS = 16384 SS_PATHELLIPSIS = 32768 SS_WORDELLIPSIS = 49152 SS_ELLIPSISMASK = 49152 STM_SETICON = 368 STM_GETICON = 369 STM_SETIMAGE = 370 STM_GETIMAGE = 371 STN_CLICKED = 0 STN_DBLCLK = 1 STN_ENABLE = 2 STN_DISABLE = 3 STM_MSGMAX = 372 DWL_MSGRESULT = 0 DWL_DLGPROC = 4 DWL_USER = 8 DDL_READWRITE = 0 DDL_READONLY = 1 DDL_HIDDEN = 2 DDL_SYSTEM = 4 DDL_DIRECTORY = 16 DDL_ARCHIVE = 32 DDL_POSTMSGS = 8192 DDL_DRIVES = 16384 DDL_EXCLUSIVE = 32768 #from winuser.h line 153 RT_CURSOR = 1 RT_BITMAP = 2 RT_ICON = 3 RT_MENU = 4 RT_DIALOG = 5 RT_STRING = 6 RT_FONTDIR = 7 RT_FONT = 8 RT_ACCELERATOR = 9 RT_RCDATA = 10 RT_MESSAGETABLE = 11 DIFFERENCE = 11 RT_GROUP_CURSOR = (RT_CURSOR + DIFFERENCE) RT_GROUP_ICON = (RT_ICON + DIFFERENCE) RT_VERSION = 16 RT_DLGINCLUDE = 17 RT_PLUGPLAY = 19 RT_VXD = 20 RT_ANICURSOR = 21 RT_ANIICON = 22 RT_HTML = 23 # from winuser.h line 218 SB_HORZ = 0 SB_VERT = 1 SB_CTL = 2 SB_BOTH = 3 SB_LINEUP = 0 SB_LINELEFT = 0 SB_LINEDOWN = 1 SB_LINERIGHT = 1 SB_PAGEUP = 2 SB_PAGELEFT = 2 SB_PAGEDOWN = 3 SB_PAGERIGHT = 3 SB_THUMBPOSITION = 4 SB_THUMBTRACK = 5 SB_TOP = 6 SB_LEFT = 6 SB_BOTTOM = 7 SB_RIGHT = 7 SB_ENDSCROLL = 8 SW_HIDE = 0 SW_SHOWNORMAL = 1 SW_NORMAL = 1 SW_SHOWMINIMIZED = 2 SW_SHOWMAXIMIZED = 3 SW_MAXIMIZE = 3 SW_SHOWNOACTIVATE = 4 SW_SHOW = 5 SW_MINIMIZE = 6 SW_SHOWMINNOACTIVE = 7 SW_SHOWNA = 8 SW_RESTORE = 9 SW_SHOWDEFAULT = 10 SW_FORCEMINIMIZE = 11 SW_MAX = 11 HIDE_WINDOW = 0 SHOW_OPENWINDOW = 1 SHOW_ICONWINDOW = 2 SHOW_FULLSCREEN = 3 SHOW_OPENNOACTIVATE = 4 SW_PARENTCLOSING = 1 SW_OTHERZOOM = 2 SW_PARENTOPENING = 3 SW_OTHERUNZOOM = 4 AW_HOR_POSITIVE = 1 AW_HOR_NEGATIVE = 2 AW_VER_POSITIVE = 4 AW_VER_NEGATIVE = 8 AW_CENTER = 16 AW_HIDE = 65536 AW_ACTIVATE = 131072 AW_SLIDE = 262144 AW_BLEND = 524288 KF_EXTENDED = 256 KF_DLGMODE = 2048 KF_MENUMODE = 4096 KF_ALTDOWN = 8192 KF_REPEAT = 16384 KF_UP = 32768 VK_LBUTTON = 1 VK_RBUTTON = 2 VK_CANCEL = 3 VK_MBUTTON = 4 VK_BACK = 8 VK_TAB = 9 VK_CLEAR = 12 VK_RETURN = 13 VK_SHIFT = 16 VK_CONTROL = 17 VK_MENU = 18 VK_PAUSE = 19 VK_CAPITAL = 20 VK_KANA = 21 VK_HANGEUL = 21 # old name - should be here for compatibility VK_HANGUL = 21 VK_JUNJA = 23 VK_FINAL = 24 VK_HANJA = 25 VK_KANJI = 25 VK_ESCAPE = 27 VK_CONVERT = 28 VK_NONCONVERT = 29 VK_ACCEPT = 30 VK_MODECHANGE = 31 VK_SPACE = 32 VK_PRIOR = 33 VK_NEXT = 34 VK_END = 35 VK_HOME = 36 VK_LEFT = 37 VK_UP = 38 VK_RIGHT = 39 VK_DOWN = 40 VK_SELECT = 41 VK_PRINT = 42 VK_EXECUTE = 43 VK_SNAPSHOT = 44 VK_INSERT = 45 VK_DELETE = 46 VK_HELP = 47 VK_LWIN = 91 VK_RWIN = 92 VK_APPS = 93 VK_NUMPAD0 = 96 VK_NUMPAD1 = 97 VK_NUMPAD2 = 98 VK_NUMPAD3 = 99 VK_NUMPAD4 = 100 VK_NUMPAD5 = 101 VK_NUMPAD6 = 102 VK_NUMPAD7 = 103 VK_NUMPAD8 = 104 VK_NUMPAD9 = 105 VK_MULTIPLY = 106 VK_ADD = 107 VK_SEPARATOR = 108 VK_SUBTRACT = 109 VK_DECIMAL = 110 VK_DIVIDE = 111 VK_F1 = 112 VK_F2 = 113 VK_F3 = 114 VK_F4 = 115 VK_F5 = 116 VK_F6 = 117 VK_F7 = 118 VK_F8 = 119 VK_F9 = 120 VK_F10 = 121 VK_F11 = 122 VK_F12 = 123 VK_F13 = 124 VK_F14 = 125 VK_F15 = 126 VK_F16 = 127 VK_F17 = 128 VK_F18 = 129 VK_F19 = 130 VK_F20 = 131 VK_F21 = 132 VK_F22 = 133 VK_F23 = 134 VK_F24 = 135 VK_NUMLOCK = 144 VK_SCROLL = 145 VK_LSHIFT = 160 VK_RSHIFT = 161 VK_LCONTROL = 162 VK_RCONTROL = 163 VK_LMENU = 164 VK_RMENU = 165 VK_PROCESSKEY = 229 VK_ATTN = 246 VK_CRSEL = 247 VK_EXSEL = 248 VK_EREOF = 249 VK_PLAY = 250 VK_ZOOM = 251 VK_NONAME = 252 VK_PA1 = 253 VK_OEM_CLEAR = 254 # multi-media related "keys" MOUSEEVENTF_XDOWN = 0x0080 MOUSEEVENTF_XUP = 0x0100 MOUSEEVENTF_WHEEL = 0x0800 VK_XBUTTON1 = 0x05 VK_XBUTTON2 = 0x06 VK_VOLUME_MUTE = 0xAD VK_VOLUME_DOWN = 0xAE VK_VOLUME_UP = 0xAF VK_MEDIA_NEXT_TRACK = 0xB0 VK_MEDIA_PREV_TRACK = 0xB1 VK_MEDIA_PLAY_PAUSE = 0xB3 VK_BROWSER_BACK = 0xA6 VK_BROWSER_FORWARD = 0xA7 WH_MIN = (-1) WH_MSGFILTER = (-1) WH_JOURNALRECORD = 0 WH_JOURNALPLAYBACK = 1 WH_KEYBOARD = 2 WH_GETMESSAGE = 3 WH_CALLWNDPROC = 4 WH_CBT = 5 WH_SYSMSGFILTER = 6 WH_MOUSE = 7 WH_HARDWARE = 8 WH_DEBUG = 9 WH_SHELL = 10 WH_FOREGROUNDIDLE = 11 WH_CALLWNDPROCRET = 12 WH_KEYBOARD_LL = 13 WH_MOUSE_LL = 14 WH_MAX = 14 WH_MINHOOK = WH_MIN WH_MAXHOOK = WH_MAX HC_ACTION = 0 HC_GETNEXT = 1 HC_SKIP = 2 HC_NOREMOVE = 3 HC_NOREM = HC_NOREMOVE HC_SYSMODALON = 4 HC_SYSMODALOFF = 5 HCBT_MOVESIZE = 0 HCBT_MINMAX = 1 HCBT_QS = 2 HCBT_CREATEWND = 3 HCBT_DESTROYWND = 4 HCBT_ACTIVATE = 5 HCBT_CLICKSKIPPED = 6 HCBT_KEYSKIPPED = 7 HCBT_SYSCOMMAND = 8 HCBT_SETFOCUS = 9 MSGF_DIALOGBOX = 0 MSGF_MESSAGEBOX = 1 MSGF_MENU = 2 #MSGF_MOVE = 3 #MSGF_SIZE = 4 MSGF_SCROLLBAR = 5 MSGF_NEXTWINDOW = 6 #MSGF_MAINLOOP = 8 MSGF_MAX = 8 MSGF_USER = 4096 HSHELL_WINDOWCREATED = 1 HSHELL_WINDOWDESTROYED = 2 HSHELL_ACTIVATESHELLWINDOW = 3 HSHELL_WINDOWACTIVATED = 4 HSHELL_GETMINRECT = 5 HSHELL_REDRAW = 6 HSHELL_TASKMAN = 7 HSHELL_LANGUAGE = 8 HSHELL_ACCESSIBILITYSTATE = 11 ACCESS_STICKYKEYS = 1 ACCESS_FILTERKEYS = 2 ACCESS_MOUSEKEYS = 3 # winuser.h line 624 LLKHF_EXTENDED = 1 LLKHF_INJECTED = 16 LLKHF_ALTDOWN = 32 LLKHF_UP = 128 LLMHF_INJECTED = 1 # line 692 HKL_PREV = 0 HKL_NEXT = 1 KLF_ACTIVATE = 1 KLF_SUBSTITUTE_OK = 2 KLF_UNLOADPREVIOUS = 4 KLF_REORDER = 8 KLF_REPLACELANG = 16 KLF_NOTELLSHELL = 128 KLF_SETFORPROCESS = 256 KL_NAMELENGTH = 9 DESKTOP_READOBJECTS = 1 DESKTOP_CREATEWINDOW = 2 DESKTOP_CREATEMENU = 4 DESKTOP_HOOKCONTROL = 8 DESKTOP_JOURNALRECORD = 16 DESKTOP_JOURNALPLAYBACK = 32 DESKTOP_ENUMERATE = 64 DESKTOP_WRITEOBJECTS = 128 DESKTOP_SWITCHDESKTOP = 256 DF_ALLOWOTHERACCOUNTHOOK = 1 WINSTA_ENUMDESKTOPS = 1 WINSTA_READATTRIBUTES = 2 WINSTA_ACCESSCLIPBOARD = 4 WINSTA_CREATEDESKTOP = 8 WINSTA_WRITEATTRIBUTES = 16 WINSTA_ACCESSGLOBALATOMS = 32 WINSTA_EXITWINDOWS = 64 WINSTA_ENUMERATE = 256 WINSTA_READSCREEN = 512 WSF_VISIBLE = 1 UOI_FLAGS = 1 UOI_NAME = 2 UOI_TYPE = 3 UOI_USER_SID = 4 GWL_WNDPROC = (-4) GWL_HINSTANCE = (-6) GWL_HWNDPARENT = (-8) GWL_STYLE = (-16) GWL_EXSTYLE = (-20) GWL_USERDATA = (-21) GWL_ID = (-12) GCL_MENUNAME = (-8) GCL_HBRBACKGROUND = (-10) GCL_HCURSOR = (-12) GCL_HICON = (-14) GCL_HMODULE = (-16) GCL_CBWNDEXTRA = (-18) GCL_CBCLSEXTRA = (-20) GCL_WNDPROC = (-24) GCL_STYLE = (-26) GCW_ATOM = (-32) GCL_HICONSM = (-34) # line 1291 WM_NULL = 0 WM_CREATE = 1 WM_DESTROY = 2 WM_MOVE = 3 WM_SIZE = 5 WM_ACTIVATE = 6 WA_INACTIVE = 0 WA_ACTIVE = 1 WA_CLICKACTIVE = 2 WM_SETFOCUS = 7 WM_KILLFOCUS = 8 WM_ENABLE = 10 WM_SETREDRAW = 11 WM_SETTEXT = 12 WM_GETTEXT = 13 WM_GETTEXTLENGTH = 14 WM_PAINT = 15 WM_CLOSE = 16 WM_QUERYENDSESSION = 17 WM_QUIT = 18 WM_QUERYOPEN = 19 WM_ERASEBKGND = 20 WM_SYSCOLORCHANGE = 21 WM_ENDSESSION = 22 WM_SHOWWINDOW = 24 WM_WININICHANGE = 26 WM_SETTINGCHANGE = WM_WININICHANGE WM_DEVMODECHANGE = 27 WM_ACTIVATEAPP = 28 WM_FONTCHANGE = 29 WM_TIMECHANGE = 30 WM_CANCELMODE = 31 WM_SETCURSOR = 32 WM_MOUSEACTIVATE = 33 WM_CHILDACTIVATE = 34 WM_QUEUESYNC = 35 WM_GETMINMAXINFO = 36 WM_PAINTICON = 38 WM_ICONERASEBKGND = 39 WM_NEXTDLGCTL = 40 WM_SPOOLERSTATUS = 42 WM_DRAWITEM = 43 WM_MEASUREITEM = 44 WM_DELETEITEM = 45 WM_VKEYTOITEM = 46 WM_CHARTOITEM = 47 WM_SETFONT = 48 WM_GETFONT = 49 WM_SETHOTKEY = 50 WM_GETHOTKEY = 51 WM_QUERYDRAGICON = 55 WM_COMPAREITEM = 57 WM_GETOBJECT = 61 WM_COMPACTING = 65 WM_COMMNOTIFY = 68 WM_WINDOWPOSCHANGING = 70 WM_WINDOWPOSCHANGED = 71 WM_POWER = 72 PWR_OK = 1 PWR_FAIL = (-1) PWR_SUSPENDREQUEST = 1 PWR_SUSPENDRESUME = 2 PWR_CRITICALRESUME = 3 WM_COPYDATA = 74 WM_CANCELJOURNAL = 75 WM_NOTIFY = 78 WM_INPUTLANGCHANGEREQUEST = 80 WM_INPUTLANGCHANGE = 81 WM_TCARD = 82 WM_HELP = 83 WM_USERCHANGED = 84 WM_NOTIFYFORMAT = 85 NFR_ANSI = 1 NFR_UNICODE = 2 NF_QUERY = 3 NF_REQUERY = 4 WM_CONTEXTMENU = 123 WM_STYLECHANGING = 124 WM_STYLECHANGED = 125 WM_DISPLAYCHANGE = 126 WM_GETICON = 127 WM_SETICON = 128 WM_NCCREATE = 129 WM_NCDESTROY = 130 WM_NCCALCSIZE = 131 WM_NCHITTEST = 132 WM_NCPAINT = 133 WM_NCACTIVATE = 134 WM_GETDLGCODE = 135 WM_SYNCPAINT = 136 WM_NCMOUSEMOVE = 160 WM_NCLBUTTONDOWN = 161 WM_NCLBUTTONUP = 162 WM_NCLBUTTONDBLCLK = 163 WM_NCRBUTTONDOWN = 164 WM_NCRBUTTONUP = 165 WM_NCRBUTTONDBLCLK = 166 WM_NCMBUTTONDOWN = 167 WM_NCMBUTTONUP = 168 WM_NCMBUTTONDBLCLK = 169 WM_KEYFIRST = 256 WM_KEYDOWN = 256 WM_KEYUP = 257 WM_CHAR = 258 WM_DEADCHAR = 259 WM_SYSKEYDOWN = 260 WM_SYSKEYUP = 261 WM_SYSCHAR = 262 WM_SYSDEADCHAR = 263 WM_KEYLAST = 264 WM_IME_STARTCOMPOSITION = 269 WM_IME_ENDCOMPOSITION = 270 WM_IME_COMPOSITION = 271 WM_IME_KEYLAST = 271 WM_INITDIALOG = 272 WM_COMMAND = 273 WM_SYSCOMMAND = 274 WM_TIMER = 275 WM_HSCROLL = 276 WM_VSCROLL = 277 WM_INITMENU = 278 WM_INITMENUPOPUP = 279 WM_MENUSELECT = 287 WM_MENUCHAR = 288 WM_ENTERIDLE = 289 WM_MENURBUTTONUP = 290 WM_MENUDRAG = 291 WM_MENUGETOBJECT = 292 WM_UNINITMENUPOPUP = 293 WM_MENUCOMMAND = 294 WM_CTLCOLORMSGBOX = 306 WM_CTLCOLOREDIT = 307 WM_CTLCOLORLISTBOX = 308 WM_CTLCOLORBTN = 309 WM_CTLCOLORDLG = 310 WM_CTLCOLORSCROLLBAR = 311 WM_CTLCOLORSTATIC = 312 WM_MOUSEFIRST = 512 WM_MOUSEMOVE = 512 WM_LBUTTONDOWN = 513 WM_LBUTTONUP = 514 WM_LBUTTONDBLCLK = 515 WM_RBUTTONDOWN = 516 WM_RBUTTONUP = 517 WM_RBUTTONDBLCLK = 518 WM_MBUTTONDOWN = 519 WM_MBUTTONUP = 520 WM_MBUTTONDBLCLK = 521 WM_MOUSEWHEEL = 522 WM_MOUSELAST = 522 WHEEL_DELTA = 120 # Value for rolling one detent WHEEL_PAGESCROLL = -1 # Scroll one page WM_PARENTNOTIFY = 528 MENULOOP_WINDOW = 0 MENULOOP_POPUP = 1 WM_ENTERMENULOOP = 529 WM_EXITMENULOOP = 530 WM_NEXTMENU = 531 WM_SIZING = 532 WM_CAPTURECHANGED = 533 WM_MOVING = 534 WM_POWERBROADCAST = 536 PBT_APMQUERYSUSPEND = 0 PBT_APMQUERYSTANDBY = 1 PBT_APMQUERYSUSPENDFAILED = 2 PBT_APMQUERYSTANDBYFAILED = 3 PBT_APMSUSPEND = 4 PBT_APMSTANDBY = 5 PBT_APMRESUMECRITICAL = 6 PBT_APMRESUMESUSPEND = 7 PBT_APMRESUMESTANDBY = 8 PBTF_APMRESUMEFROMFAILURE = 1 PBT_APMBATTERYLOW = 9 PBT_APMPOWERSTATUSCHANGE = 10 PBT_APMOEMEVENT = 11 PBT_APMRESUMEAUTOMATIC = 18 WM_DEVICECHANGE = 537 WM_MDICREATE = 544 WM_MDIDESTROY = 545 WM_MDIACTIVATE = 546 WM_MDIRESTORE = 547 WM_MDINEXT = 548 WM_MDIMAXIMIZE = 549 WM_MDITILE = 550 WM_MDICASCADE = 551 WM_MDIICONARRANGE = 552 WM_MDIGETACTIVE = 553 WM_MDISETMENU = 560 WM_ENTERSIZEMOVE = 561 WM_EXITSIZEMOVE = 562 WM_DROPFILES = 563 WM_MDIREFRESHMENU = 564 WM_IME_SETCONTEXT = 641 WM_IME_NOTIFY = 642 WM_IME_CONTROL = 643 WM_IME_COMPOSITIONFULL = 644 WM_IME_SELECT = 645 WM_IME_CHAR = 646 WM_IME_REQUEST = 648 WM_IME_KEYDOWN = 656 WM_IME_KEYUP = 657 WM_MOUSEHOVER = 673 WM_MOUSELEAVE = 675 WM_CUT = 768 WM_COPY = 769 WM_PASTE = 770 WM_CLEAR = 771 WM_UNDO = 772 WM_RENDERFORMAT = 773 WM_RENDERALLFORMATS = 774 WM_DESTROYCLIPBOARD = 775 WM_DRAWCLIPBOARD = 776 WM_PAINTCLIPBOARD = 777 WM_VSCROLLCLIPBOARD = 778 WM_SIZECLIPBOARD = 779 WM_ASKCBFORMATNAME = 780 WM_CHANGECBCHAIN = 781 WM_HSCROLLCLIPBOARD = 782 WM_QUERYNEWPALETTE = 783 WM_PALETTEISCHANGING = 784 WM_PALETTECHANGED = 785 WM_HOTKEY = 786 WM_PRINT = 791 WM_PRINTCLIENT = 792 WM_HANDHELDFIRST = 856 WM_HANDHELDLAST = 863 WM_AFXFIRST = 864 WM_AFXLAST = 895 WM_PENWINFIRST = 896 WM_PENWINLAST = 911 WM_APP = 32768 WMSZ_LEFT = 1 WMSZ_RIGHT = 2 WMSZ_TOP = 3 WMSZ_TOPLEFT = 4 WMSZ_TOPRIGHT = 5 WMSZ_BOTTOM = 6 WMSZ_BOTTOMLEFT = 7 WMSZ_BOTTOMRIGHT = 8 #ST_BEGINSWP = 0 #ST_ENDSWP = 1 HTERROR = (-2) HTTRANSPARENT = (-1) HTNOWHERE = 0 HTCLIENT = 1 HTCAPTION = 2 HTSYSMENU = 3 HTGROWBOX = 4 HTSIZE = HTGROWBOX HTMENU = 5 HTHSCROLL = 6 HTVSCROLL = 7 HTMINBUTTON = 8 HTMAXBUTTON = 9 HTLEFT = 10 HTRIGHT = 11 HTTOP = 12 HTTOPLEFT = 13 HTTOPRIGHT = 14 HTBOTTOM = 15 HTBOTTOMLEFT = 16 HTBOTTOMRIGHT = 17 HTBORDER = 18 HTREDUCE = HTMINBUTTON HTZOOM = HTMAXBUTTON HTSIZEFIRST = HTLEFT HTSIZELAST = HTBOTTOMRIGHT HTOBJECT = 19 HTCLOSE = 20 HTHELP = 21 SMTO_NORMAL = 0 SMTO_BLOCK = 1 SMTO_ABORTIFHUNG = 2 SMTO_NOTIMEOUTIFNOTHUNG = 8 MA_ACTIVATE = 1 MA_ACTIVATEANDEAT = 2 MA_NOACTIVATE = 3 MA_NOACTIVATEANDEAT = 4 ICON_SMALL = 0 ICON_BIG = 1 SIZE_RESTORED = 0 SIZE_MINIMIZED = 1 SIZE_MAXIMIZED = 2 SIZE_MAXSHOW = 3 SIZE_MAXHIDE = 4 SIZENORMAL = SIZE_RESTORED SIZEICONIC = SIZE_MINIMIZED SIZEFULLSCREEN = SIZE_MAXIMIZED SIZEZOOMSHOW = SIZE_MAXSHOW SIZEZOOMHIDE = SIZE_MAXHIDE WVR_ALIGNTOP = 16 WVR_ALIGNLEFT = 32 WVR_ALIGNBOTTOM = 64 WVR_ALIGNRIGHT = 128 WVR_HREDRAW = 256 WVR_VREDRAW = 512 WVR_REDRAW = (WVR_HREDRAW | WVR_VREDRAW) WVR_VALIDRECTS = 1024 MK_LBUTTON = 1 MK_RBUTTON = 2 MK_SHIFT = 4 MK_CONTROL = 8 MK_MBUTTON = 16 TME_HOVER = 1 TME_LEAVE = 2 TME_QUERY = 1073741824 TME_CANCEL = -2147483648 HOVER_DEFAULT = -1 WS_OVERLAPPED = 0 WS_POPUP = -2147483648 WS_CHILD = 1073741824 WS_MINIMIZE = 536870912 WS_VISIBLE = 268435456 WS_DISABLED = 134217728 WS_CLIPSIBLINGS = 67108864 WS_CLIPCHILDREN = 33554432 WS_MAXIMIZE = 16777216 WS_CAPTION = 12582912 WS_BORDER = 8388608 WS_DLGFRAME = 4194304 WS_VSCROLL = 2097152 WS_HSCROLL = 1048576 WS_SYSMENU = 524288 WS_THICKFRAME = 262144 WS_GROUP = 131072 WS_TABSTOP = 65536 WS_MINIMIZEBOX = 131072 WS_MAXIMIZEBOX = 65536 WS_TILED = WS_OVERLAPPED WS_ICONIC = WS_MINIMIZE WS_SIZEBOX = WS_THICKFRAME WS_OVERLAPPEDWINDOW = (WS_OVERLAPPED | \ WS_CAPTION | \ WS_SYSMENU | \ WS_THICKFRAME | \ WS_MINIMIZEBOX | \ WS_MAXIMIZEBOX) WS_POPUPWINDOW = (WS_POPUP | \ WS_BORDER | \ WS_SYSMENU) WS_CHILDWINDOW = (WS_CHILD) WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW WS_EX_DLGMODALFRAME = 1 WS_EX_NOPARENTNOTIFY = 4 WS_EX_TOPMOST = 8 WS_EX_ACCEPTFILES = 16 WS_EX_TRANSPARENT = 32 WS_EX_MDICHILD = 64 WS_EX_TOOLWINDOW = 128 WS_EX_WINDOWEDGE = 256 WS_EX_CLIENTEDGE = 512 WS_EX_CONTEXTHELP = 1024 WS_EX_RIGHT = 4096 WS_EX_LEFT = 0 WS_EX_RTLREADING = 8192 WS_EX_LTRREADING = 0 WS_EX_LEFTSCROLLBAR = 16384 WS_EX_RIGHTSCROLLBAR = 0 WS_EX_CONTROLPARENT = 65536 WS_EX_STATICEDGE = 131072 WS_EX_APPWINDOW = 262144 WS_EX_OVERLAPPEDWINDOW = (WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE) WS_EX_PALETTEWINDOW = (WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST) WS_EX_LAYERED = 0x00080000 WS_EX_NOINHERITLAYOUT = 0x00100000 WS_EX_LAYOUTRTL = 0x00400000 WS_EX_COMPOSITED = 0x02000000 WS_EX_NOACTIVATE = 0x08000000 CS_VREDRAW = 1 CS_HREDRAW = 2 #CS_KEYCVTWINDOW = 0x0004 CS_DBLCLKS = 8 CS_OWNDC = 32 CS_CLASSDC = 64 CS_PARENTDC = 128 #CS_NOKEYCVT = 0x0100 CS_NOCLOSE = 512 CS_SAVEBITS = 2048 CS_BYTEALIGNCLIENT = 4096 CS_BYTEALIGNWINDOW = 8192 CS_GLOBALCLASS = 16384 CS_IME = 65536 PRF_CHECKVISIBLE = 1 PRF_NONCLIENT = 2 PRF_CLIENT = 4 PRF_ERASEBKGND = 8 PRF_CHILDREN = 16 PRF_OWNED = 32 BDR_RAISEDOUTER = 1 BDR_SUNKENOUTER = 2 BDR_RAISEDINNER = 4 BDR_SUNKENINNER = 8 BDR_OUTER = 3 BDR_INNER = 12 #BDR_RAISED = 0x0005 #BDR_SUNKEN = 0x000a EDGE_RAISED = (BDR_RAISEDOUTER | BDR_RAISEDINNER) EDGE_SUNKEN = (BDR_SUNKENOUTER | BDR_SUNKENINNER) EDGE_ETCHED = (BDR_SUNKENOUTER | BDR_RAISEDINNER) EDGE_BUMP = (BDR_RAISEDOUTER | BDR_SUNKENINNER) # winuser.h line 2879 ISMEX_NOSEND = 0 ISMEX_SEND = 1 ISMEX_NOTIFY = 2 ISMEX_CALLBACK = 4 ISMEX_REPLIED = 8 CW_USEDEFAULT = -2147483648 FLASHW_STOP = 0 FLASHW_CAPTION = 1 FLASHW_TRAY = 2 FLASHW_ALL = (FLASHW_CAPTION | FLASHW_TRAY) FLASHW_TIMER = 4 FLASHW_TIMERNOFG = 12 # winuser.h line 7963 DS_ABSALIGN = 1 DS_SYSMODAL = 2 DS_LOCALEDIT = 32 DS_SETFONT = 64 DS_MODALFRAME = 128 DS_NOIDLEMSG = 256 DS_SETFOREGROUND = 512 DS_3DLOOK = 4 DS_FIXEDSYS = 8 DS_NOFAILCREATE = 16 DS_CONTROL = 1024 DS_CENTER = 2048 DS_CENTERMOUSE = 4096 DS_CONTEXTHELP = 8192 DM_GETDEFID = (WM_USER+0) DM_SETDEFID = (WM_USER+1) DM_REPOSITION = (WM_USER+2) #PSM_PAGEINFO = (WM_USER+100) #PSM_SHEETINFO = (WM_USER+101) #PSI_SETACTIVE = 0x0001 #PSI_KILLACTIVE = 0x0002 #PSI_APPLY = 0x0003 #PSI_RESET = 0x0004 #PSI_HASHELP = 0x0005 #PSI_HELP = 0x0006 #PSI_CHANGED = 0x0001 #PSI_GUISTART = 0x0002 #PSI_REBOOT = 0x0003 #PSI_GETSIBLINGS = 0x0004 DC_HASDEFID = 21323 DLGC_WANTARROWS = 1 DLGC_WANTTAB = 2 DLGC_WANTALLKEYS = 4 DLGC_WANTMESSAGE = 4 DLGC_HASSETSEL = 8 DLGC_DEFPUSHBUTTON = 16 DLGC_UNDEFPUSHBUTTON = 32 DLGC_RADIOBUTTON = 64 DLGC_WANTCHARS = 128 DLGC_STATIC = 256 DLGC_BUTTON = 8192 LB_CTLCODE = 0 LB_OKAY = 0 LB_ERR = (-1) LB_ERRSPACE = (-2) LBN_ERRSPACE = (-2) LBN_SELCHANGE = 1 LBN_DBLCLK = 2 LBN_SELCANCEL = 3 LBN_SETFOCUS = 4 LBN_KILLFOCUS = 5 LB_ADDSTRING = 384 LB_INSERTSTRING = 385 LB_DELETESTRING = 386 LB_SELITEMRANGEEX = 387 LB_RESETCONTENT = 388 LB_SETSEL = 389 LB_SETCURSEL = 390 LB_GETSEL = 391 LB_GETCURSEL = 392 LB_GETTEXT = 393 LB_GETTEXTLEN = 394 LB_GETCOUNT = 395 LB_SELECTSTRING = 396 LB_DIR = 397 LB_GETTOPINDEX = 398 LB_FINDSTRING = 399 LB_GETSELCOUNT = 400 LB_GETSELITEMS = 401 LB_SETTABSTOPS = 402 LB_GETHORIZONTALEXTENT = 403 LB_SETHORIZONTALEXTENT = 404 LB_SETCOLUMNWIDTH = 405 LB_ADDFILE = 406 LB_SETTOPINDEX = 407 LB_GETITEMRECT = 408 LB_GETITEMDATA = 409 LB_SETITEMDATA = 410 LB_SELITEMRANGE = 411 LB_SETANCHORINDEX = 412 LB_GETANCHORINDEX = 413 LB_SETCARETINDEX = 414 LB_GETCARETINDEX = 415 LB_SETITEMHEIGHT = 416 LB_GETITEMHEIGHT = 417 LB_FINDSTRINGEXACT = 418 LB_SETLOCALE = 421 LB_GETLOCALE = 422 LB_SETCOUNT = 423 LB_INITSTORAGE = 424 LB_ITEMFROMPOINT = 425 LB_MSGMAX = 432 LBS_NOTIFY = 1 LBS_SORT = 2 LBS_NOREDRAW = 4 LBS_MULTIPLESEL = 8 LBS_OWNERDRAWFIXED = 16 LBS_OWNERDRAWVARIABLE = 32 LBS_HASSTRINGS = 64 LBS_USETABSTOPS = 128 LBS_NOINTEGRALHEIGHT = 256 LBS_MULTICOLUMN = 512 LBS_WANTKEYBOARDINPUT = 1024 LBS_EXTENDEDSEL = 2048 LBS_DISABLENOSCROLL = 4096 LBS_NODATA = 8192 LBS_NOSEL = 16384 LBS_STANDARD = (LBS_NOTIFY | LBS_SORT | WS_VSCROLL | WS_BORDER) CB_OKAY = 0 CB_ERR = (-1) CB_ERRSPACE = (-2) CBN_ERRSPACE = (-1) CBN_SELCHANGE = 1 CBN_DBLCLK = 2 CBN_SETFOCUS = 3 CBN_KILLFOCUS = 4 CBN_EDITCHANGE = 5 CBN_EDITUPDATE = 6 CBN_DROPDOWN = 7 CBN_CLOSEUP = 8 CBN_SELENDOK = 9 CBN_SELENDCANCEL = 10 CBS_SIMPLE = 1 CBS_DROPDOWN = 2 CBS_DROPDOWNLIST = 3 CBS_OWNERDRAWFIXED = 16 CBS_OWNERDRAWVARIABLE = 32 CBS_AUTOHSCROLL = 64 CBS_OEMCONVERT = 128 CBS_SORT = 256 CBS_HASSTRINGS = 512 CBS_NOINTEGRALHEIGHT = 1024 CBS_DISABLENOSCROLL = 2048 CBS_UPPERCASE = 8192 CBS_LOWERCASE = 16384 CB_GETEDITSEL = 320 CB_LIMITTEXT = 321 CB_SETEDITSEL = 322 CB_ADDSTRING = 323 CB_DELETESTRING = 324 CB_DIR = 325 CB_GETCOUNT = 326 CB_GETCURSEL = 327 CB_GETLBTEXT = 328 CB_GETLBTEXTLEN = 329 CB_INSERTSTRING = 330 CB_RESETCONTENT = 331 CB_FINDSTRING = 332 CB_SELECTSTRING = 333 CB_SETCURSEL = 334 CB_SHOWDROPDOWN = 335 CB_GETITEMDATA = 336 CB_SETITEMDATA = 337 CB_GETDROPPEDCONTROLRECT = 338 CB_SETITEMHEIGHT = 339 CB_GETITEMHEIGHT = 340 CB_SETEXTENDEDUI = 341 CB_GETEXTENDEDUI = 342 CB_GETDROPPEDSTATE = 343 CB_FINDSTRINGEXACT = 344 CB_SETLOCALE = 345 CB_GETLOCALE = 346 CB_GETTOPINDEX = 347 CB_SETTOPINDEX = 348 CB_GETHORIZONTALEXTENT = 349 CB_SETHORIZONTALEXTENT = 350 CB_GETDROPPEDWIDTH = 351 CB_SETDROPPEDWIDTH = 352 CB_INITSTORAGE = 353 CB_MSGMAX = 354 SBS_HORZ = 0 SBS_VERT = 1 SBS_TOPALIGN = 2 SBS_LEFTALIGN = 2 SBS_BOTTOMALIGN = 4 SBS_RIGHTALIGN = 4 SBS_SIZEBOXTOPLEFTALIGN = 2 SBS_SIZEBOXBOTTOMRIGHTALIGN = 4 SBS_SIZEBOX = 8 SBS_SIZEGRIP = 16 SBM_SETPOS = 224 SBM_GETPOS = 225 SBM_SETRANGE = 226 SBM_SETRANGEREDRAW = 230 SBM_GETRANGE = 227 SBM_ENABLE_ARROWS = 228 SBM_SETSCROLLINFO = 233 SBM_GETSCROLLINFO = 234 SIF_RANGE = 1 SIF_PAGE = 2 SIF_POS = 4 SIF_DISABLENOSCROLL = 8 SIF_TRACKPOS = 16 SIF_ALL = (SIF_RANGE | SIF_PAGE | SIF_POS | SIF_TRACKPOS) MDIS_ALLCHILDSTYLES = 1 MDITILE_VERTICAL = 0 MDITILE_HORIZONTAL = 1 MDITILE_SKIPDISABLED = 2 IMC_GETCANDIDATEPOS = 7 IMC_SETCANDIDATEPOS = 8 IMC_GETCOMPOSITIONFONT = 9 IMC_SETCOMPOSITIONFONT = 10 IMC_GETCOMPOSITIONWINDOW = 11 IMC_SETCOMPOSITIONWINDOW = 12 IMC_GETSTATUSWINDOWPOS = 15 IMC_SETSTATUSWINDOWPOS = 16 IMC_CLOSESTATUSWINDOW = 33 IMC_OPENSTATUSWINDOW = 34 # Generated by h2py from \msvc20\include\winnt.h # hacked and split by mhammond. DELETE = (65536) READ_CONTROL = (131072) WRITE_DAC = (262144) WRITE_OWNER = (524288) SYNCHRONIZE = (1048576) STANDARD_RIGHTS_REQUIRED = (983040) STANDARD_RIGHTS_READ = (READ_CONTROL) STANDARD_RIGHTS_WRITE = (READ_CONTROL) STANDARD_RIGHTS_EXECUTE = (READ_CONTROL) STANDARD_RIGHTS_ALL = (2031616) SPECIFIC_RIGHTS_ALL = (65535) ACCESS_SYSTEM_SECURITY = (16777216) MAXIMUM_ALLOWED = (33554432) GENERIC_READ = (-2147483648) GENERIC_WRITE = (1073741824) GENERIC_EXECUTE = (536870912) GENERIC_ALL = (268435456) SERVICE_KERNEL_DRIVER = 1 SERVICE_FILE_SYSTEM_DRIVER = 2 SERVICE_ADAPTER = 4 SERVICE_RECOGNIZER_DRIVER = 8 SERVICE_DRIVER = (SERVICE_KERNEL_DRIVER | \ SERVICE_FILE_SYSTEM_DRIVER | \ SERVICE_RECOGNIZER_DRIVER) SERVICE_WIN32_OWN_PROCESS = 16 SERVICE_WIN32_SHARE_PROCESS = 32 SERVICE_WIN32 = (SERVICE_WIN32_OWN_PROCESS | \ SERVICE_WIN32_SHARE_PROCESS) SERVICE_INTERACTIVE_PROCESS = 256 SERVICE_TYPE_ALL = (SERVICE_WIN32 | \ SERVICE_ADAPTER | \ SERVICE_DRIVER | \ SERVICE_INTERACTIVE_PROCESS) SERVICE_BOOT_START = 0 SERVICE_SYSTEM_START = 1 SERVICE_AUTO_START = 2 SERVICE_DEMAND_START = 3 SERVICE_DISABLED = 4 SERVICE_ERROR_IGNORE = 0 SERVICE_ERROR_NORMAL = 1 SERVICE_ERROR_SEVERE = 2 SERVICE_ERROR_CRITICAL = 3 TAPE_ERASE_SHORT = 0 TAPE_ERASE_LONG = 1 TAPE_LOAD = 0 TAPE_UNLOAD = 1 TAPE_TENSION = 2 TAPE_LOCK = 3 TAPE_UNLOCK = 4 TAPE_FORMAT = 5 TAPE_SETMARKS = 0 TAPE_FILEMARKS = 1 TAPE_SHORT_FILEMARKS = 2 TAPE_LONG_FILEMARKS = 3 TAPE_ABSOLUTE_POSITION = 0 TAPE_LOGICAL_POSITION = 1 TAPE_PSEUDO_LOGICAL_POSITION = 2 TAPE_REWIND = 0 TAPE_ABSOLUTE_BLOCK = 1 TAPE_LOGICAL_BLOCK = 2 TAPE_PSEUDO_LOGICAL_BLOCK = 3 TAPE_SPACE_END_OF_DATA = 4 TAPE_SPACE_RELATIVE_BLOCKS = 5 TAPE_SPACE_FILEMARKS = 6 TAPE_SPACE_SEQUENTIAL_FMKS = 7 TAPE_SPACE_SETMARKS = 8 TAPE_SPACE_SEQUENTIAL_SMKS = 9 TAPE_DRIVE_FIXED = 1 TAPE_DRIVE_SELECT = 2 TAPE_DRIVE_INITIATOR = 4 TAPE_DRIVE_ERASE_SHORT = 16 TAPE_DRIVE_ERASE_LONG = 32 TAPE_DRIVE_ERASE_BOP_ONLY = 64 TAPE_DRIVE_ERASE_IMMEDIATE = 128 TAPE_DRIVE_TAPE_CAPACITY = 256 TAPE_DRIVE_TAPE_REMAINING = 512 TAPE_DRIVE_FIXED_BLOCK = 1024 TAPE_DRIVE_VARIABLE_BLOCK = 2048 TAPE_DRIVE_WRITE_PROTECT = 4096 TAPE_DRIVE_EOT_WZ_SIZE = 8192 TAPE_DRIVE_ECC = 65536 TAPE_DRIVE_COMPRESSION = 131072 TAPE_DRIVE_PADDING = 262144 TAPE_DRIVE_REPORT_SMKS = 524288 TAPE_DRIVE_GET_ABSOLUTE_BLK = 1048576 TAPE_DRIVE_GET_LOGICAL_BLK = 2097152 TAPE_DRIVE_SET_EOT_WZ_SIZE = 4194304 TAPE_DRIVE_LOAD_UNLOAD = -2147483647 TAPE_DRIVE_TENSION = -2147483646 TAPE_DRIVE_LOCK_UNLOCK = -2147483644 TAPE_DRIVE_REWIND_IMMEDIATE = -2147483640 TAPE_DRIVE_SET_BLOCK_SIZE = -2147483632 TAPE_DRIVE_LOAD_UNLD_IMMED = -2147483616 TAPE_DRIVE_TENSION_IMMED = -2147483584 TAPE_DRIVE_LOCK_UNLK_IMMED = -2147483520 TAPE_DRIVE_SET_ECC = -2147483392 TAPE_DRIVE_SET_COMPRESSION = -2147483136 TAPE_DRIVE_SET_PADDING = -2147482624 TAPE_DRIVE_SET_REPORT_SMKS = -2147481600 TAPE_DRIVE_ABSOLUTE_BLK = -2147479552 TAPE_DRIVE_ABS_BLK_IMMED = -2147475456 TAPE_DRIVE_LOGICAL_BLK = -2147467264 TAPE_DRIVE_LOG_BLK_IMMED = -2147450880 TAPE_DRIVE_END_OF_DATA = -2147418112 TAPE_DRIVE_RELATIVE_BLKS = -2147352576 TAPE_DRIVE_FILEMARKS = -2147221504 TAPE_DRIVE_SEQUENTIAL_FMKS = -2146959360 TAPE_DRIVE_SETMARKS = -2146435072 TAPE_DRIVE_SEQUENTIAL_SMKS = -2145386496 TAPE_DRIVE_REVERSE_POSITION = -2143289344 TAPE_DRIVE_SPACE_IMMEDIATE = -2139095040 TAPE_DRIVE_WRITE_SETMARKS = -2130706432 TAPE_DRIVE_WRITE_FILEMARKS = -2113929216 TAPE_DRIVE_WRITE_SHORT_FMKS = -2080374784 TAPE_DRIVE_WRITE_LONG_FMKS = -2013265920 TAPE_DRIVE_WRITE_MARK_IMMED = -1879048192 TAPE_DRIVE_FORMAT = -1610612736 TAPE_DRIVE_FORMAT_IMMEDIATE = -1073741824 TAPE_FIXED_PARTITIONS = 0 TAPE_SELECT_PARTITIONS = 1 TAPE_INITIATOR_PARTITIONS = 2 # Generated by h2py from \msvc20\include\winnt.h # hacked and split by mhammond. APPLICATION_ERROR_MASK = 536870912 ERROR_SEVERITY_SUCCESS = 0 ERROR_SEVERITY_INFORMATIONAL = 1073741824 ERROR_SEVERITY_WARNING = -2147483648 ERROR_SEVERITY_ERROR = -1073741824 MINCHAR = 128 MAXCHAR = 127 MINSHORT = 32768 MAXSHORT = 32767 MINLONG = -2147483648 MAXLONG = 2147483647 MAXBYTE = 255 MAXWORD = 65535 MAXDWORD = -1 LANG_NEUTRAL = 0 LANG_BULGARIAN = 2 LANG_CHINESE = 4 LANG_CROATIAN = 26 LANG_CZECH = 5 LANG_DANISH = 6 LANG_DUTCH = 19 LANG_ENGLISH = 9 LANG_FINNISH = 11 LANG_FRENCH = 12 LANG_GERMAN = 7 LANG_GREEK = 8 LANG_HUNGARIAN = 14 LANG_ICELANDIC = 15 LANG_ITALIAN = 16 LANG_JAPANESE = 17 LANG_KOREAN = 18 LANG_NORWEGIAN = 20 LANG_POLISH = 21 LANG_PORTUGUESE = 22 LANG_ROMANIAN = 24 LANG_RUSSIAN = 25 LANG_SLOVAK = 27 LANG_SLOVENIAN = 36 LANG_SPANISH = 10 LANG_SWEDISH = 29 LANG_TURKISH = 31 SUBLANG_NEUTRAL = 0 SUBLANG_DEFAULT = 1 SUBLANG_SYS_DEFAULT = 2 SUBLANG_CHINESE_TRADITIONAL = 1 SUBLANG_CHINESE_SIMPLIFIED = 2 SUBLANG_CHINESE_HONGKONG = 3 SUBLANG_CHINESE_SINGAPORE = 4 SUBLANG_DUTCH = 1 SUBLANG_DUTCH_BELGIAN = 2 SUBLANG_ENGLISH_US = 1 SUBLANG_ENGLISH_UK = 2 SUBLANG_ENGLISH_AUS = 3 SUBLANG_ENGLISH_CAN = 4 SUBLANG_ENGLISH_NZ = 5 SUBLANG_ENGLISH_EIRE = 6 SUBLANG_FRENCH = 1 SUBLANG_FRENCH_BELGIAN = 2 SUBLANG_FRENCH_CANADIAN = 3 SUBLANG_FRENCH_SWISS = 4 SUBLANG_GERMAN = 1 SUBLANG_GERMAN_SWISS = 2 SUBLANG_GERMAN_AUSTRIAN = 3 SUBLANG_ITALIAN = 1 SUBLANG_ITALIAN_SWISS = 2 SUBLANG_NORWEGIAN_BOKMAL = 1 SUBLANG_NORWEGIAN_NYNORSK = 2 SUBLANG_PORTUGUESE = 2 SUBLANG_PORTUGUESE_BRAZILIAN = 1 SUBLANG_SPANISH = 1 SUBLANG_SPANISH_MEXICAN = 2 SUBLANG_SPANISH_MODERN = 3 SORT_DEFAULT = 0 SORT_JAPANESE_XJIS = 0 SORT_JAPANESE_UNICODE = 1 SORT_CHINESE_BIG5 = 0 SORT_CHINESE_UNICODE = 1 SORT_KOREAN_KSC = 0 SORT_KOREAN_UNICODE = 1 def PRIMARYLANGID(lgid): return ((lgid) & 1023) def SUBLANGID(lgid): return ((lgid) >> 10) NLS_VALID_LOCALE_MASK = 1048575 CONTEXT_PORTABLE_32BIT = 1048576 CONTEXT_ALPHA = 131072 CONTEXT_CONTROL = (CONTEXT_ALPHA | 1) CONTEXT_FLOATING_POINT = (CONTEXT_ALPHA | 2) CONTEXT_INTEGER = (CONTEXT_ALPHA | 4) CONTEXT_FULL = (CONTEXT_CONTROL | CONTEXT_FLOATING_POINT | CONTEXT_INTEGER) SIZE_OF_80387_REGISTERS = 80 CONTEXT_FULL = (CONTEXT_CONTROL | CONTEXT_FLOATING_POINT | CONTEXT_INTEGER) CONTEXT_CONTROL = 1 CONTEXT_FLOATING_POINT = 2 CONTEXT_INTEGER = 4 CONTEXT_FULL = (CONTEXT_CONTROL | CONTEXT_FLOATING_POINT | CONTEXT_INTEGER) PROCESS_TERMINATE = (1) PROCESS_CREATE_THREAD = (2) PROCESS_VM_OPERATION = (8) PROCESS_VM_READ = (16) PROCESS_VM_WRITE = (32) PROCESS_DUP_HANDLE = (64) PROCESS_CREATE_PROCESS = (128) PROCESS_SET_QUOTA = (256) PROCESS_SET_INFORMATION = (512) PROCESS_QUERY_INFORMATION = (1024) PROCESS_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 4095) THREAD_TERMINATE = (1) THREAD_SUSPEND_RESUME = (2) THREAD_GET_CONTEXT = (8) THREAD_SET_CONTEXT = (16) THREAD_SET_INFORMATION = (32) THREAD_QUERY_INFORMATION = (64) THREAD_SET_THREAD_TOKEN = (128) THREAD_IMPERSONATE = (256) THREAD_DIRECT_IMPERSONATION = (512) TLS_MINIMUM_AVAILABLE = 64 EVENT_MODIFY_STATE = 2 MUTANT_QUERY_STATE = 1 SEMAPHORE_MODIFY_STATE = 2 TIME_ZONE_ID_UNKNOWN = 0 TIME_ZONE_ID_STANDARD = 1 TIME_ZONE_ID_DAYLIGHT = 2 PROCESSOR_INTEL_386 = 386 PROCESSOR_INTEL_486 = 486 PROCESSOR_INTEL_PENTIUM = 586 PROCESSOR_INTEL_860 = 860 PROCESSOR_MIPS_R2000 = 2000 PROCESSOR_MIPS_R3000 = 3000 PROCESSOR_MIPS_R4000 = 4000 PROCESSOR_ALPHA_21064 = 21064 PROCESSOR_PPC_601 = 601 PROCESSOR_PPC_603 = 603 PROCESSOR_PPC_604 = 604 PROCESSOR_PPC_620 = 620 SECTION_QUERY = 1 SECTION_MAP_WRITE = 2 SECTION_MAP_READ = 4 SECTION_MAP_EXECUTE = 8 SECTION_EXTEND_SIZE = 16 PAGE_NOACCESS = 1 PAGE_READONLY = 2 PAGE_READWRITE = 4 PAGE_WRITECOPY = 8 PAGE_EXECUTE = 16 PAGE_EXECUTE_READ = 32 PAGE_EXECUTE_READWRITE = 64 PAGE_EXECUTE_WRITECOPY = 128 PAGE_GUARD = 256 PAGE_NOCACHE = 512 MEM_COMMIT = 4096 MEM_RESERVE = 8192 MEM_DECOMMIT = 16384 MEM_RELEASE = 32768 MEM_FREE = 65536 MEM_PRIVATE = 131072 MEM_MAPPED = 262144 MEM_TOP_DOWN = 1048576 # Generated by h2py from \msvc20\include\winnt.h # hacked and split by mhammond. SEC_FILE = 8388608 SEC_IMAGE = 16777216 SEC_RESERVE = 67108864 SEC_COMMIT = 134217728 SEC_NOCACHE = 268435456 MEM_IMAGE = SEC_IMAGE FILE_SHARE_READ = 1 FILE_SHARE_WRITE = 2 FILE_SHARE_DELETE = 4 FILE_ATTRIBUTE_READONLY = 1 FILE_ATTRIBUTE_HIDDEN = 2 FILE_ATTRIBUTE_SYSTEM = 4 FILE_ATTRIBUTE_DIRECTORY = 16 FILE_ATTRIBUTE_ARCHIVE = 32 FILE_ATTRIBUTE_NORMAL = 128 FILE_ATTRIBUTE_TEMPORARY = 256 FILE_ATTRIBUTE_ATOMIC_WRITE = 512 FILE_ATTRIBUTE_XACTION_WRITE = 1024 FILE_ATTRIBUTE_COMPRESSED = 2048 FILE_NOTIFY_CHANGE_FILE_NAME = 1 FILE_NOTIFY_CHANGE_DIR_NAME = 2 FILE_NOTIFY_CHANGE_ATTRIBUTES = 4 FILE_NOTIFY_CHANGE_SIZE = 8 FILE_NOTIFY_CHANGE_LAST_WRITE = 16 FILE_NOTIFY_CHANGE_SECURITY = 256 FILE_CASE_SENSITIVE_SEARCH = 1 FILE_CASE_PRESERVED_NAMES = 2 FILE_UNICODE_ON_DISK = 4 FILE_PERSISTENT_ACLS = 8 FILE_FILE_COMPRESSION = 16 FILE_VOLUME_IS_COMPRESSED = 32768 IO_COMPLETION_MODIFY_STATE = 2 DUPLICATE_CLOSE_SOURCE = 1 DUPLICATE_SAME_ACCESS = 2 SID_MAX_SUB_AUTHORITIES = (15) SECURITY_NULL_RID = (0) SECURITY_WORLD_RID = (0) SECURITY_LOCAL_RID = (0X00000000) SECURITY_CREATOR_OWNER_RID = (0) SECURITY_CREATOR_GROUP_RID = (1) SECURITY_DIALUP_RID = (1) SECURITY_NETWORK_RID = (2) SECURITY_BATCH_RID = (3) SECURITY_INTERACTIVE_RID = (4) SECURITY_SERVICE_RID = (6) SECURITY_ANONYMOUS_LOGON_RID = (7) SECURITY_LOGON_IDS_RID = (5) SECURITY_LOGON_IDS_RID_COUNT = (3) SECURITY_LOCAL_SYSTEM_RID = (18) SECURITY_NT_NON_UNIQUE = (21) SECURITY_BUILTIN_DOMAIN_RID = (32) DOMAIN_USER_RID_ADMIN = (500) DOMAIN_USER_RID_GUEST = (501) DOMAIN_GROUP_RID_ADMINS = (512) DOMAIN_GROUP_RID_USERS = (513) DOMAIN_GROUP_RID_GUESTS = (514) DOMAIN_ALIAS_RID_ADMINS = (544) DOMAIN_ALIAS_RID_USERS = (545) DOMAIN_ALIAS_RID_GUESTS = (546) DOMAIN_ALIAS_RID_POWER_USERS = (547) DOMAIN_ALIAS_RID_ACCOUNT_OPS = (548) DOMAIN_ALIAS_RID_SYSTEM_OPS = (549) DOMAIN_ALIAS_RID_PRINT_OPS = (550) DOMAIN_ALIAS_RID_BACKUP_OPS = (551) DOMAIN_ALIAS_RID_REPLICATOR = (552) SE_GROUP_MANDATORY = (1) SE_GROUP_ENABLED_BY_DEFAULT = (2) SE_GROUP_ENABLED = (4) SE_GROUP_OWNER = (8) SE_GROUP_LOGON_ID = (-1073741824) ACL_REVISION = (2) ACL_REVISION1 = (1) ACL_REVISION2 = (2) ACCESS_ALLOWED_ACE_TYPE = (0) ACCESS_DENIED_ACE_TYPE = (1) SYSTEM_AUDIT_ACE_TYPE = (2) SYSTEM_ALARM_ACE_TYPE = (3) OBJECT_INHERIT_ACE = (1) CONTAINER_INHERIT_ACE = (2) NO_PROPAGATE_INHERIT_ACE = (4) INHERIT_ONLY_ACE = (8) VALID_INHERIT_FLAGS = (15) SUCCESSFUL_ACCESS_ACE_FLAG = (64) FAILED_ACCESS_ACE_FLAG = (128) SECURITY_DESCRIPTOR_REVISION = (1) SECURITY_DESCRIPTOR_REVISION1 = (1) SECURITY_DESCRIPTOR_MIN_LENGTH = (20) SE_OWNER_DEFAULTED = (1) SE_GROUP_DEFAULTED = (2) SE_DACL_PRESENT = (4) SE_DACL_DEFAULTED = (8) SE_SACL_PRESENT = (16) SE_SACL_DEFAULTED = (32) SE_SELF_RELATIVE = (32768) SE_PRIVILEGE_ENABLED_BY_DEFAULT = (1) SE_PRIVILEGE_ENABLED = (2) SE_PRIVILEGE_USED_FOR_ACCESS = (-2147483648) PRIVILEGE_SET_ALL_NECESSARY = (1) SE_CREATE_TOKEN_NAME = "SeCreateTokenPrivilege" SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege" SE_LOCK_MEMORY_NAME = "SeLockMemoryPrivilege" SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege" SE_UNSOLICITED_INPUT_NAME = "SeUnsolicitedInputPrivilege" SE_MACHINE_ACCOUNT_NAME = "SeMachineAccountPrivilege" SE_TCB_NAME = "SeTcbPrivilege" SE_SECURITY_NAME = "SeSecurityPrivilege" SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege" SE_LOAD_DRIVER_NAME = "SeLoadDriverPrivilege" SE_SYSTEM_PROFILE_NAME = "SeSystemProfilePrivilege" SE_SYSTEMTIME_NAME = "SeSystemtimePrivilege" SE_PROF_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege" SE_INC_BASE_PRIORITY_NAME = "SeIncreaseBasePriorityPrivilege" SE_CREATE_PAGEFILE_NAME = "SeCreatePagefilePrivilege" SE_CREATE_PERMANENT_NAME = "SeCreatePermanentPrivilege" SE_BACKUP_NAME = "SeBackupPrivilege" SE_RESTORE_NAME = "SeRestorePrivilege" SE_SHUTDOWN_NAME = "SeShutdownPrivilege" SE_DEBUG_NAME = "SeDebugPrivilege" SE_AUDIT_NAME = "SeAuditPrivilege" SE_SYSTEM_ENVIRONMENT_NAME = "SeSystemEnvironmentPrivilege" SE_CHANGE_NOTIFY_NAME = "SeChangeNotifyPrivilege" SE_REMOTE_SHUTDOWN_NAME = "SeRemoteShutdownPrivilege" TOKEN_ASSIGN_PRIMARY = (1) TOKEN_DUPLICATE = (2) TOKEN_IMPERSONATE = (4) TOKEN_QUERY = (8) TOKEN_QUERY_SOURCE = (16) TOKEN_ADJUST_PRIVILEGES = (32) TOKEN_ADJUST_GROUPS = (64) TOKEN_ADJUST_DEFAULT = (128) TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED |\ TOKEN_ASSIGN_PRIMARY |\ TOKEN_DUPLICATE |\ TOKEN_IMPERSONATE |\ TOKEN_QUERY |\ TOKEN_QUERY_SOURCE |\ TOKEN_ADJUST_PRIVILEGES |\ TOKEN_ADJUST_GROUPS |\ TOKEN_ADJUST_DEFAULT) TOKEN_READ = (STANDARD_RIGHTS_READ |\ TOKEN_QUERY) TOKEN_WRITE = (STANDARD_RIGHTS_WRITE |\ TOKEN_ADJUST_PRIVILEGES |\ TOKEN_ADJUST_GROUPS |\ TOKEN_ADJUST_DEFAULT) TOKEN_EXECUTE = (STANDARD_RIGHTS_EXECUTE) TOKEN_SOURCE_LENGTH = 8 KEY_QUERY_VALUE = (1) KEY_SET_VALUE = (2) KEY_CREATE_SUB_KEY = (4) KEY_ENUMERATE_SUB_KEYS = (8) KEY_NOTIFY = (16) KEY_CREATE_LINK = (32) KEY_READ = ((STANDARD_RIGHTS_READ |\ KEY_QUERY_VALUE |\ KEY_ENUMERATE_SUB_KEYS |\ KEY_NOTIFY) \ & \ (~SYNCHRONIZE)) KEY_WRITE = ((STANDARD_RIGHTS_WRITE |\ KEY_SET_VALUE |\ KEY_CREATE_SUB_KEY) \ & \ (~SYNCHRONIZE)) KEY_EXECUTE = ((KEY_READ) \ & \ (~SYNCHRONIZE)) KEY_ALL_ACCESS = ((STANDARD_RIGHTS_ALL |\ KEY_QUERY_VALUE |\ KEY_SET_VALUE |\ KEY_CREATE_SUB_KEY |\ KEY_ENUMERATE_SUB_KEYS |\ KEY_NOTIFY |\ KEY_CREATE_LINK) \ & \ (~SYNCHRONIZE)) REG_NOTIFY_CHANGE_ATTRIBUTES = (2) REG_NOTIFY_CHANGE_SECURITY = (8) REG_RESOURCE_REQUIREMENTS_LIST = ( 10 ) REG_NONE = ( 0 ) # No value type REG_SZ = ( 1 ) # Unicode nul terminated string REG_EXPAND_SZ = ( 2 ) # Unicode nul terminated string # (with environment variable references) REG_BINARY = ( 3 ) # Free form binary REG_DWORD = ( 4 ) # 32-bit number REG_DWORD_LITTLE_ENDIAN = ( 4 ) # 32-bit number (same as REG_DWORD) REG_DWORD_BIG_ENDIAN = ( 5 ) # 32-bit number REG_LINK = ( 6 ) # Symbolic Link (unicode) REG_MULTI_SZ = ( 7 ) # Multiple Unicode strings REG_RESOURCE_LIST = ( 8 ) # Resource list in the resource map REG_FULL_RESOURCE_DESCRIPTOR =( 9 ) # Resource list in the hardware description REG_RESOURCE_REQUIREMENTS_LIST = ( 10 ) REG_QWORD = ( 11 ) # 64-bit number REG_QWORD_LITTLE_ENDIAN = ( 11 ) # 64-bit number (same as REG_QWORD) # Generated by h2py from \msvc20\include\winnt.h # hacked and split by mhammond. # Included from string.h _NLSCMPERROR = 2147483647 NULL = 0 HEAP_NO_SERIALIZE = 1 HEAP_GROWABLE = 2 HEAP_GENERATE_EXCEPTIONS = 4 HEAP_ZERO_MEMORY = 8 HEAP_REALLOC_IN_PLACE_ONLY = 16 HEAP_TAIL_CHECKING_ENABLED = 32 HEAP_FREE_CHECKING_ENABLED = 64 HEAP_DISABLE_COALESCE_ON_FREE = 128 IS_TEXT_UNICODE_ASCII16 = 1 IS_TEXT_UNICODE_REVERSE_ASCII16 = 16 IS_TEXT_UNICODE_STATISTICS = 2 IS_TEXT_UNICODE_REVERSE_STATISTICS = 32 IS_TEXT_UNICODE_CONTROLS = 4 IS_TEXT_UNICODE_REVERSE_CONTROLS = 64 IS_TEXT_UNICODE_SIGNATURE = 8 IS_TEXT_UNICODE_REVERSE_SIGNATURE = 128 IS_TEXT_UNICODE_ILLEGAL_CHARS = 256 IS_TEXT_UNICODE_ODD_LENGTH = 512 IS_TEXT_UNICODE_DBCS_LEADBYTE = 1024 IS_TEXT_UNICODE_NULL_BYTES = 4096 IS_TEXT_UNICODE_UNICODE_MASK = 15 IS_TEXT_UNICODE_REVERSE_MASK = 240 IS_TEXT_UNICODE_NOT_UNICODE_MASK = 3840 IS_TEXT_UNICODE_NOT_ASCII_MASK = 61440 COMPRESSION_FORMAT_NONE = (0) COMPRESSION_FORMAT_DEFAULT = (1) COMPRESSION_FORMAT_LZNT1 = (2) COMPRESSION_ENGINE_STANDARD = (0) COMPRESSION_ENGINE_MAXIMUM = (256) MESSAGE_RESOURCE_UNICODE = 1 RTL_CRITSECT_TYPE = 0 RTL_RESOURCE_TYPE = 1 DLL_PROCESS_ATTACH = 1 DLL_THREAD_ATTACH = 2 DLL_THREAD_DETACH = 3 DLL_PROCESS_DETACH = 0 EVENTLOG_SEQUENTIAL_READ = 0X0001 EVENTLOG_SEEK_READ = 0X0002 EVENTLOG_FORWARDS_READ = 0X0004 EVENTLOG_BACKWARDS_READ = 0X0008 EVENTLOG_SUCCESS = 0X0000 EVENTLOG_ERROR_TYPE = 1 EVENTLOG_WARNING_TYPE = 2 EVENTLOG_INFORMATION_TYPE = 4 EVENTLOG_AUDIT_SUCCESS = 8 EVENTLOG_AUDIT_FAILURE = 16 EVENTLOG_START_PAIRED_EVENT = 1 EVENTLOG_END_PAIRED_EVENT = 2 EVENTLOG_END_ALL_PAIRED_EVENTS = 4 EVENTLOG_PAIRED_EVENT_ACTIVE = 8 EVENTLOG_PAIRED_EVENT_INACTIVE = 16 # Generated by h2py from \msvc20\include\winnt.h # hacked and split by mhammond. OWNER_SECURITY_INFORMATION = (0X00000001) GROUP_SECURITY_INFORMATION = (0X00000002) DACL_SECURITY_INFORMATION = (0X00000004) SACL_SECURITY_INFORMATION = (0X00000008) IMAGE_SIZEOF_FILE_HEADER = 20 IMAGE_FILE_MACHINE_UNKNOWN = 0 IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16 IMAGE_SIZEOF_ROM_OPTIONAL_HEADER = 56 IMAGE_SIZEOF_STD_OPTIONAL_HEADER = 28 IMAGE_SIZEOF_NT_OPTIONAL_HEADER = 224 IMAGE_NT_OPTIONAL_HDR_MAGIC = 267 IMAGE_ROM_OPTIONAL_HDR_MAGIC = 263 IMAGE_SIZEOF_SHORT_NAME = 8 IMAGE_SIZEOF_SECTION_HEADER = 40 IMAGE_SIZEOF_SYMBOL = 18 IMAGE_SYM_CLASS_NULL = 0 IMAGE_SYM_CLASS_AUTOMATIC = 1 IMAGE_SYM_CLASS_EXTERNAL = 2 IMAGE_SYM_CLASS_STATIC = 3 IMAGE_SYM_CLASS_REGISTER = 4 IMAGE_SYM_CLASS_EXTERNAL_DEF = 5 IMAGE_SYM_CLASS_LABEL = 6 IMAGE_SYM_CLASS_UNDEFINED_LABEL = 7 IMAGE_SYM_CLASS_MEMBER_OF_STRUCT = 8 IMAGE_SYM_CLASS_ARGUMENT = 9 IMAGE_SYM_CLASS_STRUCT_TAG = 10 IMAGE_SYM_CLASS_MEMBER_OF_UNION = 11 IMAGE_SYM_CLASS_UNION_TAG = 12 IMAGE_SYM_CLASS_TYPE_DEFINITION = 13 IMAGE_SYM_CLASS_UNDEFINED_STATIC = 14 IMAGE_SYM_CLASS_ENUM_TAG = 15 IMAGE_SYM_CLASS_MEMBER_OF_ENUM = 16 IMAGE_SYM_CLASS_REGISTER_PARAM = 17 IMAGE_SYM_CLASS_BIT_FIELD = 18 IMAGE_SYM_CLASS_BLOCK = 100 IMAGE_SYM_CLASS_FUNCTION = 101 IMAGE_SYM_CLASS_END_OF_STRUCT = 102 IMAGE_SYM_CLASS_FILE = 103 IMAGE_SYM_CLASS_SECTION = 104 IMAGE_SYM_CLASS_WEAK_EXTERNAL = 105 N_BTMASK = 017 N_TMASK = 060 N_TMASK1 = 0300 N_TMASK2 = 0360 N_BTSHFT = 4 N_TSHIFT = 2 IMAGE_SIZEOF_AUX_SYMBOL = 18 IMAGE_COMDAT_SELECT_NODUPLICATES = 1 IMAGE_COMDAT_SELECT_ANY = 2 IMAGE_COMDAT_SELECT_SAME_SIZE = 3 IMAGE_COMDAT_SELECT_EXACT_MATCH = 4 IMAGE_COMDAT_SELECT_ASSOCIATIVE = 5 IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY = 1 IMAGE_WEAK_EXTERN_SEARCH_LIBRARY = 2 IMAGE_WEAK_EXTERN_SEARCH_ALIAS = 3 IMAGE_SIZEOF_RELOCATION = 10 IMAGE_REL_I386_SECTION = 012 IMAGE_REL_I386_SECREL = 013 IMAGE_REL_MIPS_REFHALF = 01 IMAGE_REL_MIPS_REFWORD = 02 IMAGE_REL_MIPS_JMPADDR = 03 IMAGE_REL_MIPS_REFHI = 04 IMAGE_REL_MIPS_REFLO = 05 IMAGE_REL_MIPS_GPREL = 06 IMAGE_REL_MIPS_LITERAL = 07 IMAGE_REL_MIPS_SECTION = 012 IMAGE_REL_MIPS_SECREL = 013 IMAGE_REL_MIPS_REFWORDNB = 042 IMAGE_REL_MIPS_PAIR = 045 IMAGE_REL_ALPHA_ABSOLUTE = 0 IMAGE_REL_ALPHA_REFLONG = 1 IMAGE_REL_ALPHA_REFQUAD = 2 IMAGE_REL_ALPHA_GPREL32 = 3 IMAGE_REL_ALPHA_LITERAL = 4 IMAGE_REL_ALPHA_LITUSE = 5 IMAGE_REL_ALPHA_GPDISP = 6 IMAGE_REL_ALPHA_BRADDR = 7 IMAGE_REL_ALPHA_HINT = 8 IMAGE_REL_ALPHA_INLINE_REFLONG = 9 IMAGE_REL_ALPHA_REFHI = 10 IMAGE_REL_ALPHA_REFLO = 11 IMAGE_REL_ALPHA_PAIR = 12 IMAGE_REL_ALPHA_MATCH = 13 IMAGE_REL_ALPHA_SECTION = 14 IMAGE_REL_ALPHA_SECREL = 15 IMAGE_REL_ALPHA_REFLONGNB = 16 IMAGE_SIZEOF_BASE_RELOCATION = 8 IMAGE_REL_BASED_ABSOLUTE = 0 IMAGE_REL_BASED_HIGH = 1 IMAGE_REL_BASED_LOW = 2 IMAGE_REL_BASED_HIGHLOW = 3 IMAGE_REL_BASED_HIGHADJ = 4 IMAGE_REL_BASED_MIPS_JMPADDR = 5 IMAGE_SIZEOF_LINENUMBER = 6 IMAGE_ARCHIVE_START_SIZE = 8 IMAGE_ARCHIVE_START = "!<arch>\n" IMAGE_ARCHIVE_END = "`\n" IMAGE_ARCHIVE_PAD = "\n" IMAGE_ARCHIVE_LINKER_MEMBER = "/ " IMAGE_ARCHIVE_LONGNAMES_MEMBER = "// " IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR = 60 IMAGE_ORDINAL_FLAG = -2147483648 def IMAGE_SNAP_BY_ORDINAL(Ordinal): return ((Ordinal & IMAGE_ORDINAL_FLAG) != 0) def IMAGE_ORDINAL(Ordinal): return (Ordinal & 65535) IMAGE_RESOURCE_NAME_IS_STRING = -2147483648 IMAGE_RESOURCE_DATA_IS_DIRECTORY = -2147483648 IMAGE_DEBUG_TYPE_UNKNOWN = 0 IMAGE_DEBUG_TYPE_COFF = 1 IMAGE_DEBUG_TYPE_CODEVIEW = 2 IMAGE_DEBUG_TYPE_FPO = 3 IMAGE_DEBUG_TYPE_MISC = 4 IMAGE_DEBUG_TYPE_EXCEPTION = 5 IMAGE_DEBUG_TYPE_FIXUP = 6 IMAGE_DEBUG_TYPE_OMAP_TO_SRC = 7 IMAGE_DEBUG_TYPE_OMAP_FROM_SRC = 8 FRAME_FPO = 0 FRAME_TRAP = 1 FRAME_TSS = 2 SIZEOF_RFPO_DATA = 16 IMAGE_DEBUG_MISC_EXENAME = 1 IMAGE_SEPARATE_DEBUG_SIGNATURE = 18756 # Generated by h2py from \msvcnt\include\wingdi.h # hacked and split manually by mhammond. NEWFRAME = 1 ABORTDOC = 2 NEXTBAND = 3 SETCOLORTABLE = 4 GETCOLORTABLE = 5 FLUSHOUTPUT = 6 DRAFTMODE = 7 QUERYESCSUPPORT = 8 SETABORTPROC = 9 STARTDOC = 10 ENDDOC = 11 GETPHYSPAGESIZE = 12 GETPRINTINGOFFSET = 13 GETSCALINGFACTOR = 14 MFCOMMENT = 15 GETPENWIDTH = 16 SETCOPYCOUNT = 17 SELECTPAPERSOURCE = 18 DEVICEDATA = 19 PASSTHROUGH = 19 GETTECHNOLGY = 20 GETTECHNOLOGY = 20 SETLINECAP = 21 SETLINEJOIN = 22 SETMITERLIMIT = 23 BANDINFO = 24 DRAWPATTERNRECT = 25 GETVECTORPENSIZE = 26 GETVECTORBRUSHSIZE = 27 ENABLEDUPLEX = 28 GETSETPAPERBINS = 29 GETSETPRINTORIENT = 30 ENUMPAPERBINS = 31 SETDIBSCALING = 32 EPSPRINTING = 33 ENUMPAPERMETRICS = 34 GETSETPAPERMETRICS = 35 POSTSCRIPT_DATA = 37 POSTSCRIPT_IGNORE = 38 MOUSETRAILS = 39 GETDEVICEUNITS = 42 GETEXTENDEDTEXTMETRICS = 256 GETEXTENTTABLE = 257 GETPAIRKERNTABLE = 258 GETTRACKKERNTABLE = 259 EXTTEXTOUT = 512 GETFACENAME = 513 DOWNLOADFACE = 514 ENABLERELATIVEWIDTHS = 768 ENABLEPAIRKERNING = 769 SETKERNTRACK = 770 SETALLJUSTVALUES = 771 SETCHARSET = 772 STRETCHBLT = 2048 GETSETSCREENPARAMS = 3072 BEGIN_PATH = 4096 CLIP_TO_PATH = 4097 END_PATH = 4098 EXT_DEVICE_CAPS = 4099 RESTORE_CTM = 4100 SAVE_CTM = 4101 SET_ARC_DIRECTION = 4102 SET_BACKGROUND_COLOR = 4103 SET_POLY_MODE = 4104 SET_SCREEN_ANGLE = 4105 SET_SPREAD = 4106 TRANSFORM_CTM = 4107 SET_CLIP_BOX = 4108 SET_BOUNDS = 4109 SET_MIRROR_MODE = 4110 OPENCHANNEL = 4110 DOWNLOADHEADER = 4111 CLOSECHANNEL = 4112 POSTSCRIPT_PASSTHROUGH = 4115 ENCAPSULATED_POSTSCRIPT = 4116 SP_NOTREPORTED = 16384 SP_ERROR = (-1) SP_APPABORT = (-2) SP_USERABORT = (-3) SP_OUTOFDISK = (-4) SP_OUTOFMEMORY = (-5) PR_JOBSTATUS = 0 OBJ_PEN = 1 OBJ_BRUSH = 2 OBJ_DC = 3 OBJ_METADC = 4 OBJ_PAL = 5 OBJ_FONT = 6 OBJ_BITMAP = 7 OBJ_REGION = 8 OBJ_METAFILE = 9 OBJ_MEMDC = 10 OBJ_EXTPEN = 11 OBJ_ENHMETADC = 12 OBJ_ENHMETAFILE = 13 MWT_IDENTITY = 1 MWT_LEFTMULTIPLY = 2 MWT_RIGHTMULTIPLY = 3 MWT_MIN = MWT_IDENTITY MWT_MAX = MWT_RIGHTMULTIPLY BI_RGB = 0 BI_RLE8 = 1 BI_RLE4 = 2 BI_BITFIELDS = 3 TMPF_FIXED_PITCH = 1 TMPF_VECTOR = 2 TMPF_DEVICE = 8 TMPF_TRUETYPE = 4 NTM_REGULAR = 64 NTM_BOLD = 32 NTM_ITALIC = 1 LF_FACESIZE = 32 LF_FULLFACESIZE = 64 OUT_DEFAULT_PRECIS = 0 OUT_STRING_PRECIS = 1 OUT_CHARACTER_PRECIS = 2 OUT_STROKE_PRECIS = 3 OUT_TT_PRECIS = 4 OUT_DEVICE_PRECIS = 5 OUT_RASTER_PRECIS = 6 OUT_TT_ONLY_PRECIS = 7 OUT_OUTLINE_PRECIS = 8 CLIP_DEFAULT_PRECIS = 0 CLIP_CHARACTER_PRECIS = 1 CLIP_STROKE_PRECIS = 2 CLIP_MASK = 15 CLIP_LH_ANGLES = (1<<4) CLIP_TT_ALWAYS = (2<<4) CLIP_EMBEDDED = (8<<4) DEFAULT_QUALITY = 0 DRAFT_QUALITY = 1 PROOF_QUALITY = 2 NONANTIALIASED_QUALITY = 3 ANTIALIASED_QUALITY = 4 CLEARTYPE_QUALITY = 5 CLEARTYPE_NATURAL_QUALITY = 6 DEFAULT_PITCH = 0 FIXED_PITCH = 1 VARIABLE_PITCH = 2 ANSI_CHARSET = 0 DEFAULT_CHARSET = 1 SYMBOL_CHARSET = 2 SHIFTJIS_CHARSET = 128 HANGEUL_CHARSET = 129 CHINESEBIG5_CHARSET = 136 OEM_CHARSET = 255 JOHAB_CHARSET = 130 HEBREW_CHARSET = 177 ARABIC_CHARSET = 178 GREEK_CHARSET = 161 TURKISH_CHARSET = 162 VIETNAMESE_CHARSET = 163 THAI_CHARSET = 222 EASTEUROPE_CHARSET = 238 RUSSIAN_CHARSET = 204 MAC_CHARSET = 77 BALTIC_CHARSET = 186 FF_DONTCARE = (0<<4) FF_ROMAN = (1<<4) FF_SWISS = (2<<4) FF_MODERN = (3<<4) FF_SCRIPT = (4<<4) FF_DECORATIVE = (5<<4) FW_DONTCARE = 0 FW_THIN = 100 FW_EXTRALIGHT = 200 FW_LIGHT = 300 FW_NORMAL = 400 FW_MEDIUM = 500 FW_SEMIBOLD = 600 FW_BOLD = 700 FW_EXTRABOLD = 800 FW_HEAVY = 900 FW_ULTRALIGHT = FW_EXTRALIGHT FW_REGULAR = FW_NORMAL FW_DEMIBOLD = FW_SEMIBOLD FW_ULTRABOLD = FW_EXTRABOLD FW_BLACK = FW_HEAVY # Generated by h2py from \msvcnt\include\wingdi.h # hacked and split manually by mhammond. BS_SOLID = 0 BS_NULL = 1 BS_HOLLOW = BS_NULL BS_HATCHED = 2 BS_PATTERN = 3 BS_INDEXED = 4 BS_DIBPATTERN = 5 BS_DIBPATTERNPT = 6 BS_PATTERN8X8 = 7 BS_DIBPATTERN8X8 = 8 HS_HORIZONTAL = 0 HS_VERTICAL = 1 HS_FDIAGONAL = 2 HS_BDIAGONAL = 3 HS_CROSS = 4 HS_DIAGCROSS = 5 HS_FDIAGONAL1 = 6 HS_BDIAGONAL1 = 7 HS_SOLID = 8 HS_DENSE1 = 9 HS_DENSE2 = 10 HS_DENSE3 = 11 HS_DENSE4 = 12 HS_DENSE5 = 13 HS_DENSE6 = 14 HS_DENSE7 = 15 HS_DENSE8 = 16 HS_NOSHADE = 17 HS_HALFTONE = 18 HS_SOLIDCLR = 19 HS_DITHEREDCLR = 20 HS_SOLIDTEXTCLR = 21 HS_DITHEREDTEXTCLR = 22 HS_SOLIDBKCLR = 23 HS_DITHEREDBKCLR = 24 HS_API_MAX = 25 PS_SOLID = 0 PS_DASH = 1 PS_DOT = 2 PS_DASHDOT = 3 PS_DASHDOTDOT = 4 PS_NULL = 5 PS_INSIDEFRAME = 6 PS_USERSTYLE = 7 PS_ALTERNATE = 8 PS_STYLE_MASK = 15 PS_ENDCAP_ROUND = 0 PS_ENDCAP_SQUARE = 256 PS_ENDCAP_FLAT = 512 PS_ENDCAP_MASK = 3840 PS_JOIN_ROUND = 0 PS_JOIN_BEVEL = 4096 PS_JOIN_MITER = 8192 PS_JOIN_MASK = 61440 PS_COSMETIC = 0 PS_GEOMETRIC = 65536 PS_TYPE_MASK = 983040 AD_COUNTERCLOCKWISE = 1 AD_CLOCKWISE = 2 DRIVERVERSION = 0 TECHNOLOGY = 2 HORZSIZE = 4 VERTSIZE = 6 HORZRES = 8 VERTRES = 10 BITSPIXEL = 12 PLANES = 14 NUMBRUSHES = 16 NUMPENS = 18 NUMMARKERS = 20 NUMFONTS = 22 NUMCOLORS = 24 PDEVICESIZE = 26 CURVECAPS = 28 LINECAPS = 30 POLYGONALCAPS = 32 TEXTCAPS = 34 CLIPCAPS = 36 RASTERCAPS = 38 ASPECTX = 40 ASPECTY = 42 ASPECTXY = 44 LOGPIXELSX = 88 LOGPIXELSY = 90 SIZEPALETTE = 104 NUMRESERVED = 106 COLORRES = 108 DT_PLOTTER = 0 DT_RASDISPLAY = 1 DT_RASPRINTER = 2 DT_RASCAMERA = 3 DT_CHARSTREAM = 4 DT_METAFILE = 5 DT_DISPFILE = 6 CC_NONE = 0 CC_CIRCLES = 1 CC_PIE = 2 CC_CHORD = 4 CC_ELLIPSES = 8 CC_WIDE = 16 CC_STYLED = 32 CC_WIDESTYLED = 64 CC_INTERIORS = 128 CC_ROUNDRECT = 256 LC_NONE = 0 LC_POLYLINE = 2 LC_MARKER = 4 LC_POLYMARKER = 8 LC_WIDE = 16 LC_STYLED = 32 LC_WIDESTYLED = 64 LC_INTERIORS = 128 PC_NONE = 0 PC_POLYGON = 1 PC_RECTANGLE = 2 PC_WINDPOLYGON = 4 PC_TRAPEZOID = 4 PC_SCANLINE = 8 PC_WIDE = 16 PC_STYLED = 32 PC_WIDESTYLED = 64 PC_INTERIORS = 128 CP_NONE = 0 CP_RECTANGLE = 1 CP_REGION = 2 TC_OP_CHARACTER = 1 TC_OP_STROKE = 2 TC_CP_STROKE = 4 TC_CR_90 = 8 TC_CR_ANY = 16 TC_SF_X_YINDEP = 32 TC_SA_DOUBLE = 64 TC_SA_INTEGER = 128 TC_SA_CONTIN = 256 TC_EA_DOUBLE = 512 TC_IA_ABLE = 1024 TC_UA_ABLE = 2048 TC_SO_ABLE = 4096 TC_RA_ABLE = 8192 TC_VA_ABLE = 16384 TC_RESERVED = 32768 TC_SCROLLBLT = 65536 RC_BITBLT = 1 RC_BANDING = 2 RC_SCALING = 4 RC_BITMAP64 = 8 RC_GDI20_OUTPUT = 16 RC_GDI20_STATE = 32 RC_SAVEBITMAP = 64 RC_DI_BITMAP = 128 RC_PALETTE = 256 RC_DIBTODEV = 512 RC_BIGFONT = 1024 RC_STRETCHBLT = 2048 RC_FLOODFILL = 4096 RC_STRETCHDIB = 8192 RC_OP_DX_OUTPUT = 16384 RC_DEVBITS = 32768 DIB_RGB_COLORS = 0 DIB_PAL_COLORS = 1 DIB_PAL_INDICES = 2 DIB_PAL_PHYSINDICES = 2 DIB_PAL_LOGINDICES = 4 SYSPAL_ERROR = 0 SYSPAL_STATIC = 1 SYSPAL_NOSTATIC = 2 CBM_CREATEDIB = 2 CBM_INIT = 4 FLOODFILLBORDER = 0 FLOODFILLSURFACE = 1 CCHDEVICENAME = 32 CCHFORMNAME = 32 # Generated by h2py from \msvcnt\include\wingdi.h # hacked and split manually by mhammond. # DEVMODE.dmFields DM_SPECVERSION = 800 DM_ORIENTATION = 1 DM_PAPERSIZE = 2 DM_PAPERLENGTH = 4 DM_PAPERWIDTH = 8 DM_SCALE = 16 DM_POSITION = 32 DM_NUP = 64 DM_DISPLAYORIENTATION = 128 DM_COPIES = 256 DM_DEFAULTSOURCE = 512 DM_PRINTQUALITY = 1024 DM_COLOR = 2048 DM_DUPLEX = 4096 DM_YRESOLUTION = 8192 DM_TTOPTION = 16384 DM_COLLATE = 32768 DM_FORMNAME = 65536 DM_LOGPIXELS = 131072 DM_BITSPERPEL = 262144 DM_PELSWIDTH = 524288 DM_PELSHEIGHT = 1048576 DM_DISPLAYFLAGS = 2097152 DM_DISPLAYFREQUENCY = 4194304 DM_ICMMETHOD = 8388608 DM_ICMINTENT = 16777216 DM_MEDIATYPE = 33554432 DM_DITHERTYPE = 67108864 DM_PANNINGWIDTH = 134217728 DM_PANNINGHEIGHT = 268435456 DM_DISPLAYFIXEDOUTPUT = 536870912 # DEVMODE.dmOrientation DMORIENT_PORTRAIT = 1 DMORIENT_LANDSCAPE = 2 # DEVMODE.dmDisplayOrientation DMDO_DEFAULT = 0 DMDO_90 = 1 DMDO_180 = 2 DMDO_270 = 3 # DEVMODE.dmDisplayFixedOutput DMDFO_DEFAULT = 0 DMDFO_STRETCH = 1 DMDFO_CENTER = 2 # DEVMODE.dmPaperSize DMPAPER_LETTER = 1 DMPAPER_LETTERSMALL = 2 DMPAPER_TABLOID = 3 DMPAPER_LEDGER = 4 DMPAPER_LEGAL = 5 DMPAPER_STATEMENT = 6 DMPAPER_EXECUTIVE = 7 DMPAPER_A3 = 8 DMPAPER_A4 = 9 DMPAPER_A4SMALL = 10 DMPAPER_A5 = 11 DMPAPER_B4 = 12 DMPAPER_B5 = 13 DMPAPER_FOLIO = 14 DMPAPER_QUARTO = 15 DMPAPER_10X14 = 16 DMPAPER_11X17 = 17 DMPAPER_NOTE = 18 DMPAPER_ENV_9 = 19 DMPAPER_ENV_10 = 20 DMPAPER_ENV_11 = 21 DMPAPER_ENV_12 = 22 DMPAPER_ENV_14 = 23 DMPAPER_CSHEET = 24 DMPAPER_DSHEET = 25 DMPAPER_ESHEET = 26 DMPAPER_ENV_DL = 27 DMPAPER_ENV_C5 = 28 DMPAPER_ENV_C3 = 29 DMPAPER_ENV_C4 = 30 DMPAPER_ENV_C6 = 31 DMPAPER_ENV_C65 = 32 DMPAPER_ENV_B4 = 33 DMPAPER_ENV_B5 = 34 DMPAPER_ENV_B6 = 35 DMPAPER_ENV_ITALY = 36 DMPAPER_ENV_MONARCH = 37 DMPAPER_ENV_PERSONAL = 38 DMPAPER_FANFOLD_US = 39 DMPAPER_FANFOLD_STD_GERMAN = 40 DMPAPER_FANFOLD_LGL_GERMAN = 41 DMPAPER_ISO_B4 = 42 DMPAPER_JAPANESE_POSTCARD = 43 DMPAPER_9X11 = 44 DMPAPER_10X11 = 45 DMPAPER_15X11 = 46 DMPAPER_ENV_INVITE = 47 DMPAPER_RESERVED_48 = 48 DMPAPER_RESERVED_49 = 49 DMPAPER_LETTER_EXTRA = 50 DMPAPER_LEGAL_EXTRA = 51 DMPAPER_TABLOID_EXTRA = 52 DMPAPER_A4_EXTRA = 53 DMPAPER_LETTER_TRANSVERSE = 54 DMPAPER_A4_TRANSVERSE = 55 DMPAPER_LETTER_EXTRA_TRANSVERSE = 56 DMPAPER_A_PLUS = 57 DMPAPER_B_PLUS = 58 DMPAPER_LETTER_PLUS = 59 DMPAPER_A4_PLUS = 60 DMPAPER_A5_TRANSVERSE = 61 DMPAPER_B5_TRANSVERSE = 62 DMPAPER_A3_EXTRA = 63 DMPAPER_A5_EXTRA = 64 DMPAPER_B5_EXTRA = 65 DMPAPER_A2 = 66 DMPAPER_A3_TRANSVERSE = 67 DMPAPER_A3_EXTRA_TRANSVERSE = 68 DMPAPER_DBL_JAPANESE_POSTCARD = 69 DMPAPER_A6 = 70 DMPAPER_JENV_KAKU2 = 71 DMPAPER_JENV_KAKU3 = 72 DMPAPER_JENV_CHOU3 = 73 DMPAPER_JENV_CHOU4 = 74 DMPAPER_LETTER_ROTATED = 75 DMPAPER_A3_ROTATED = 76 DMPAPER_A4_ROTATED = 77 DMPAPER_A5_ROTATED = 78 DMPAPER_B4_JIS_ROTATED = 79 DMPAPER_B5_JIS_ROTATED = 80 DMPAPER_JAPANESE_POSTCARD_ROTATED = 81 DMPAPER_DBL_JAPANESE_POSTCARD_ROTATED = 82 DMPAPER_A6_ROTATED = 83 DMPAPER_JENV_KAKU2_ROTATED = 84 DMPAPER_JENV_KAKU3_ROTATED = 85 DMPAPER_JENV_CHOU3_ROTATED = 86 DMPAPER_JENV_CHOU4_ROTATED = 87 DMPAPER_B6_JIS = 88 DMPAPER_B6_JIS_ROTATED = 89 DMPAPER_12X11 = 90 DMPAPER_JENV_YOU4 = 91 DMPAPER_JENV_YOU4_ROTATED = 92 DMPAPER_P16K = 93 DMPAPER_P32K = 94 DMPAPER_P32KBIG = 95 DMPAPER_PENV_1 = 96 DMPAPER_PENV_2 = 97 DMPAPER_PENV_3 = 98 DMPAPER_PENV_4 = 99 DMPAPER_PENV_5 = 100 DMPAPER_PENV_6 = 101 DMPAPER_PENV_7 = 102 DMPAPER_PENV_8 = 103 DMPAPER_PENV_9 = 104 DMPAPER_PENV_10 = 105 DMPAPER_P16K_ROTATED = 106 DMPAPER_P32K_ROTATED = 107 DMPAPER_P32KBIG_ROTATED = 108 DMPAPER_PENV_1_ROTATED = 109 DMPAPER_PENV_2_ROTATED = 110 DMPAPER_PENV_3_ROTATED = 111 DMPAPER_PENV_4_ROTATED = 112 DMPAPER_PENV_5_ROTATED = 113 DMPAPER_PENV_6_ROTATED = 114 DMPAPER_PENV_7_ROTATED = 115 DMPAPER_PENV_8_ROTATED = 116 DMPAPER_PENV_9_ROTATED = 117 DMPAPER_PENV_10_ROTATED = 118 DMPAPER_LAST = DMPAPER_PENV_10_ROTATED DMPAPER_USER = 256 # DEVMODE.dmDefaultSource DMBIN_UPPER = 1 DMBIN_ONLYONE = 1 DMBIN_LOWER = 2 DMBIN_MIDDLE = 3 DMBIN_MANUAL = 4 DMBIN_ENVELOPE = 5 DMBIN_ENVMANUAL = 6 DMBIN_AUTO = 7 DMBIN_TRACTOR = 8 DMBIN_SMALLFMT = 9 DMBIN_LARGEFMT = 10 DMBIN_LARGECAPACITY = 11 DMBIN_CASSETTE = 14 DMBIN_LAST = DMBIN_CASSETTE DMBIN_USER = 256 # DEVMODE.dmPrintQuality DMRES_DRAFT = (-1) DMRES_LOW = (-2) DMRES_MEDIUM = (-3) DMRES_HIGH = (-4) # DEVMODE.dmColor DMCOLOR_MONOCHROME = 1 DMCOLOR_COLOR = 2 # DEVMODE.dmDuplex DMDUP_SIMPLEX = 1 DMDUP_VERTICAL = 2 DMDUP_HORIZONTAL = 3 # DEVMODE.dmTTOption DMTT_BITMAP = 1 DMTT_DOWNLOAD = 2 DMTT_SUBDEV = 3 DMTT_DOWNLOAD_OUTLINE = 4 # DEVMODE.dmCollate DMCOLLATE_FALSE = 0 DMCOLLATE_TRUE = 1 # DEVMODE.dmDisplayFlags DM_GRAYSCALE = 1 DM_INTERLACED = 2 # DEVMODE.dmICMMethod DMICMMETHOD_NONE = 1 DMICMMETHOD_SYSTEM = 2 DMICMMETHOD_DRIVER = 3 DMICMMETHOD_DEVICE = 4 DMICMMETHOD_USER = 256 # DEVMODE.dmICMIntent DMICM_SATURATE = 1 DMICM_CONTRAST = 2 DMICM_COLORIMETRIC = 3 DMICM_ABS_COLORIMETRIC = 4 DMICM_USER = 256 # DEVMODE.dmMediaType DMMEDIA_STANDARD = 1 DMMEDIA_TRANSPARENCY = 2 DMMEDIA_GLOSSY = 3 DMMEDIA_USER = 256 # DEVMODE.dmDitherType DMDITHER_NONE = 1 DMDITHER_COARSE = 2 DMDITHER_FINE = 3 DMDITHER_LINEART = 4 DMDITHER_ERRORDIFFUSION = 5 DMDITHER_RESERVED6 = 6 DMDITHER_RESERVED7 = 7 DMDITHER_RESERVED8 = 8 DMDITHER_RESERVED9 = 9 DMDITHER_GRAYSCALE = 10 DMDITHER_USER = 256 # DEVMODE.dmNup DMNUP_SYSTEM = 1 DMNUP_ONEUP = 2 RDH_RECTANGLES = 1 GGO_METRICS = 0 GGO_BITMAP = 1 GGO_NATIVE = 2 TT_POLYGON_TYPE = 24 TT_PRIM_LINE = 1 TT_PRIM_QSPLINE = 2 TT_AVAILABLE = 1 TT_ENABLED = 2 DM_UPDATE = 1 DM_COPY = 2 DM_PROMPT = 4 DM_MODIFY = 8 DM_IN_BUFFER = DM_MODIFY DM_IN_PROMPT = DM_PROMPT DM_OUT_BUFFER = DM_COPY DM_OUT_DEFAULT = DM_UPDATE # DISPLAY_DEVICE.StateFlags DISPLAY_DEVICE_ATTACHED_TO_DESKTOP = 1 DISPLAY_DEVICE_MULTI_DRIVER = 2 DISPLAY_DEVICE_PRIMARY_DEVICE = 4 DISPLAY_DEVICE_MIRRORING_DRIVER = 8 DISPLAY_DEVICE_VGA_COMPATIBLE = 16 DISPLAY_DEVICE_REMOVABLE = 32 DISPLAY_DEVICE_MODESPRUNED = 134217728 DISPLAY_DEVICE_REMOTE = 67108864 DISPLAY_DEVICE_DISCONNECT = 33554432 # DeviceCapabilities types DC_FIELDS = 1 DC_PAPERS = 2 DC_PAPERSIZE = 3 DC_MINEXTENT = 4 DC_MAXEXTENT = 5 DC_BINS = 6 DC_DUPLEX = 7 DC_SIZE = 8 DC_EXTRA = 9 DC_VERSION = 10 DC_DRIVER = 11 DC_BINNAMES = 12 DC_ENUMRESOLUTIONS = 13 DC_FILEDEPENDENCIES = 14 DC_TRUETYPE = 15 DC_PAPERNAMES = 16 DC_ORIENTATION = 17 DC_COPIES = 18 DC_BINADJUST = 19 DC_EMF_COMPLIANT = 20 DC_DATATYPE_PRODUCED = 21 DC_COLLATE = 22 DC_MANUFACTURER = 23 DC_MODEL = 24 DC_PERSONALITY = 25 DC_PRINTRATE = 26 DC_PRINTRATEUNIT = 27 DC_PRINTERMEM = 28 DC_MEDIAREADY = 29 DC_STAPLE = 30 DC_PRINTRATEPPM = 31 DC_COLORDEVICE = 32 DC_NUP = 33 DC_MEDIATYPENAMES = 34 DC_MEDIATYPES = 35 PRINTRATEUNIT_PPM = 1 PRINTRATEUNIT_CPS = 2 PRINTRATEUNIT_LPM = 3 PRINTRATEUNIT_IPM = 4 # TrueType constants DCTT_BITMAP = 1 DCTT_DOWNLOAD = 2 DCTT_SUBDEV = 4 DCTT_DOWNLOAD_OUTLINE = 8 CA_NEGATIVE = 1 CA_LOG_FILTER = 2 ILLUMINANT_DEVICE_DEFAULT = 0 ILLUMINANT_A = 1 ILLUMINANT_B = 2 ILLUMINANT_C = 3 ILLUMINANT_D50 = 4 ILLUMINANT_D55 = 5 ILLUMINANT_D65 = 6 ILLUMINANT_D75 = 7 ILLUMINANT_F2 = 8 ILLUMINANT_MAX_INDEX = ILLUMINANT_F2 ILLUMINANT_TUNGSTEN = ILLUMINANT_A ILLUMINANT_DAYLIGHT = ILLUMINANT_C ILLUMINANT_FLUORESCENT = ILLUMINANT_F2 ILLUMINANT_NTSC = ILLUMINANT_C # Generated by h2py from \msvcnt\include\wingdi.h # hacked and split manually by mhammond. FONTMAPPER_MAX = 10 ENHMETA_SIGNATURE = 1179469088 ENHMETA_STOCK_OBJECT = -2147483648 EMR_HEADER = 1 EMR_POLYBEZIER = 2 EMR_POLYGON = 3 EMR_POLYLINE = 4 EMR_POLYBEZIERTO = 5 EMR_POLYLINETO = 6 EMR_POLYPOLYLINE = 7 EMR_POLYPOLYGON = 8 EMR_SETWINDOWEXTEX = 9 EMR_SETWINDOWORGEX = 10 EMR_SETVIEWPORTEXTEX = 11 EMR_SETVIEWPORTORGEX = 12 EMR_SETBRUSHORGEX = 13 EMR_EOF = 14 EMR_SETPIXELV = 15 EMR_SETMAPPERFLAGS = 16 EMR_SETMAPMODE = 17 EMR_SETBKMODE = 18 EMR_SETPOLYFILLMODE = 19 EMR_SETROP2 = 20 EMR_SETSTRETCHBLTMODE = 21 EMR_SETTEXTALIGN = 22 EMR_SETCOLORADJUSTMENT = 23 EMR_SETTEXTCOLOR = 24 EMR_SETBKCOLOR = 25 EMR_OFFSETCLIPRGN = 26 EMR_MOVETOEX = 27 EMR_SETMETARGN = 28 EMR_EXCLUDECLIPRECT = 29 EMR_INTERSECTCLIPRECT = 30 EMR_SCALEVIEWPORTEXTEX = 31 EMR_SCALEWINDOWEXTEX = 32 EMR_SAVEDC = 33 EMR_RESTOREDC = 34 EMR_SETWORLDTRANSFORM = 35 EMR_MODIFYWORLDTRANSFORM = 36 EMR_SELECTOBJECT = 37 EMR_CREATEPEN = 38 EMR_CREATEBRUSHINDIRECT = 39 EMR_DELETEOBJECT = 40 EMR_ANGLEARC = 41 EMR_ELLIPSE = 42 EMR_RECTANGLE = 43 EMR_ROUNDRECT = 44 EMR_ARC = 45 EMR_CHORD = 46 EMR_PIE = 47 EMR_SELECTPALETTE = 48 EMR_CREATEPALETTE = 49 EMR_SETPALETTEENTRIES = 50 EMR_RESIZEPALETTE = 51 EMR_REALIZEPALETTE = 52 EMR_EXTFLOODFILL = 53 EMR_LINETO = 54 EMR_ARCTO = 55 EMR_POLYDRAW = 56 EMR_SETARCDIRECTION = 57 EMR_SETMITERLIMIT = 58 EMR_BEGINPATH = 59 EMR_ENDPATH = 60 EMR_CLOSEFIGURE = 61 EMR_FILLPATH = 62 EMR_STROKEANDFILLPATH = 63 EMR_STROKEPATH = 64 EMR_FLATTENPATH = 65 EMR_WIDENPATH = 66 EMR_SELECTCLIPPATH = 67 EMR_ABORTPATH = 68 EMR_GDICOMMENT = 70 EMR_FILLRGN = 71 EMR_FRAMERGN = 72 EMR_INVERTRGN = 73 EMR_PAINTRGN = 74 EMR_EXTSELECTCLIPRGN = 75 EMR_BITBLT = 76 EMR_STRETCHBLT = 77 EMR_MASKBLT = 78 EMR_PLGBLT = 79 EMR_SETDIBITSTODEVICE = 80 EMR_STRETCHDIBITS = 81 EMR_EXTCREATEFONTINDIRECTW = 82 EMR_EXTTEXTOUTA = 83 EMR_EXTTEXTOUTW = 84 EMR_POLYBEZIER16 = 85 EMR_POLYGON16 = 86 EMR_POLYLINE16 = 87 EMR_POLYBEZIERTO16 = 88 EMR_POLYLINETO16 = 89 EMR_POLYPOLYLINE16 = 90 EMR_POLYPOLYGON16 = 91 EMR_POLYDRAW16 = 92 EMR_CREATEMONOBRUSH = 93 EMR_CREATEDIBPATTERNBRUSHPT = 94 EMR_EXTCREATEPEN = 95 EMR_POLYTEXTOUTA = 96 EMR_POLYTEXTOUTW = 97 EMR_MIN = 1 EMR_MAX = 97 # Generated by h2py from \msvcnt\include\wingdi.h # hacked and split manually by mhammond. PANOSE_COUNT = 10 PAN_FAMILYTYPE_INDEX = 0 PAN_SERIFSTYLE_INDEX = 1 PAN_WEIGHT_INDEX = 2 PAN_PROPORTION_INDEX = 3 PAN_CONTRAST_INDEX = 4 PAN_STROKEVARIATION_INDEX = 5 PAN_ARMSTYLE_INDEX = 6 PAN_LETTERFORM_INDEX = 7 PAN_MIDLINE_INDEX = 8 PAN_XHEIGHT_INDEX = 9 PAN_CULTURE_LATIN = 0 PAN_ANY = 0 PAN_NO_FIT = 1 PAN_FAMILY_TEXT_DISPLAY = 2 PAN_FAMILY_SCRIPT = 3 PAN_FAMILY_DECORATIVE = 4 PAN_FAMILY_PICTORIAL = 5 PAN_SERIF_COVE = 2 PAN_SERIF_OBTUSE_COVE = 3 PAN_SERIF_SQUARE_COVE = 4 PAN_SERIF_OBTUSE_SQUARE_COVE = 5 PAN_SERIF_SQUARE = 6 PAN_SERIF_THIN = 7 PAN_SERIF_BONE = 8 PAN_SERIF_EXAGGERATED = 9 PAN_SERIF_TRIANGLE = 10 PAN_SERIF_NORMAL_SANS = 11 PAN_SERIF_OBTUSE_SANS = 12 PAN_SERIF_PERP_SANS = 13 PAN_SERIF_FLARED = 14 PAN_SERIF_ROUNDED = 15 PAN_WEIGHT_VERY_LIGHT = 2 PAN_WEIGHT_LIGHT = 3 PAN_WEIGHT_THIN = 4 PAN_WEIGHT_BOOK = 5 PAN_WEIGHT_MEDIUM = 6 PAN_WEIGHT_DEMI = 7 PAN_WEIGHT_BOLD = 8 PAN_WEIGHT_HEAVY = 9 PAN_WEIGHT_BLACK = 10 PAN_WEIGHT_NORD = 11 PAN_PROP_OLD_STYLE = 2 PAN_PROP_MODERN = 3 PAN_PROP_EVEN_WIDTH = 4 PAN_PROP_EXPANDED = 5 PAN_PROP_CONDENSED = 6 PAN_PROP_VERY_EXPANDED = 7 PAN_PROP_VERY_CONDENSED = 8 PAN_PROP_MONOSPACED = 9 PAN_CONTRAST_NONE = 2 PAN_CONTRAST_VERY_LOW = 3 PAN_CONTRAST_LOW = 4 PAN_CONTRAST_MEDIUM_LOW = 5 PAN_CONTRAST_MEDIUM = 6 PAN_CONTRAST_MEDIUM_HIGH = 7 PAN_CONTRAST_HIGH = 8 PAN_CONTRAST_VERY_HIGH = 9 PAN_STROKE_GRADUAL_DIAG = 2 PAN_STROKE_GRADUAL_TRAN = 3 PAN_STROKE_GRADUAL_VERT = 4 PAN_STROKE_GRADUAL_HORZ = 5 PAN_STROKE_RAPID_VERT = 6 PAN_STROKE_RAPID_HORZ = 7 PAN_STROKE_INSTANT_VERT = 8 PAN_STRAIGHT_ARMS_HORZ = 2 PAN_STRAIGHT_ARMS_WEDGE = 3 PAN_STRAIGHT_ARMS_VERT = 4 PAN_STRAIGHT_ARMS_SINGLE_SERIF = 5 PAN_STRAIGHT_ARMS_DOUBLE_SERIF = 6 PAN_BENT_ARMS_HORZ = 7 PAN_BENT_ARMS_WEDGE = 8 PAN_BENT_ARMS_VERT = 9 PAN_BENT_ARMS_SINGLE_SERIF = 10 PAN_BENT_ARMS_DOUBLE_SERIF = 11 PAN_LETT_NORMAL_CONTACT = 2 PAN_LETT_NORMAL_WEIGHTED = 3 PAN_LETT_NORMAL_BOXED = 4 PAN_LETT_NORMAL_FLATTENED = 5 PAN_LETT_NORMAL_ROUNDED = 6 PAN_LETT_NORMAL_OFF_CENTER = 7 PAN_LETT_NORMAL_SQUARE = 8 PAN_LETT_OBLIQUE_CONTACT = 9 PAN_LETT_OBLIQUE_WEIGHTED = 10 PAN_LETT_OBLIQUE_BOXED = 11 PAN_LETT_OBLIQUE_FLATTENED = 12 PAN_LETT_OBLIQUE_ROUNDED = 13 PAN_LETT_OBLIQUE_OFF_CENTER = 14 PAN_LETT_OBLIQUE_SQUARE = 15 PAN_MIDLINE_STANDARD_TRIMMED = 2 PAN_MIDLINE_STANDARD_POINTED = 3 PAN_MIDLINE_STANDARD_SERIFED = 4 PAN_MIDLINE_HIGH_TRIMMED = 5 PAN_MIDLINE_HIGH_POINTED = 6 PAN_MIDLINE_HIGH_SERIFED = 7 PAN_MIDLINE_CONSTANT_TRIMMED = 8 PAN_MIDLINE_CONSTANT_POINTED = 9 PAN_MIDLINE_CONSTANT_SERIFED = 10 PAN_MIDLINE_LOW_TRIMMED = 11 PAN_MIDLINE_LOW_POINTED = 12 PAN_MIDLINE_LOW_SERIFED = 13 PAN_XHEIGHT_CONSTANT_SMALL = 2 PAN_XHEIGHT_CONSTANT_STD = 3 PAN_XHEIGHT_CONSTANT_LARGE = 4 PAN_XHEIGHT_DUCKING_SMALL = 5 PAN_XHEIGHT_DUCKING_STD = 6 PAN_XHEIGHT_DUCKING_LARGE = 7 ELF_VENDOR_SIZE = 4 ELF_VERSION = 0 ELF_CULTURE_LATIN = 0 RASTER_FONTTYPE = 1 DEVICE_FONTTYPE = 2 TRUETYPE_FONTTYPE = 4 def PALETTEINDEX(i): return ((16777216 | (i))) PC_RESERVED = 1 PC_EXPLICIT = 2 PC_NOCOLLAPSE = 4 def GetRValue(rgb): return rgb & 0xff def GetGValue(rgb): return (rgb >> 8) & 0xff def GetBValue(rgb): return (rgb >> 16) & 0xff TRANSPARENT = 1 OPAQUE = 2 BKMODE_LAST = 2 GM_COMPATIBLE = 1 GM_ADVANCED = 2 GM_LAST = 2 PT_CLOSEFIGURE = 1 PT_LINETO = 2 PT_BEZIERTO = 4 PT_MOVETO = 6 MM_TEXT = 1 MM_LOMETRIC = 2 MM_HIMETRIC = 3 MM_LOENGLISH = 4 MM_HIENGLISH = 5 MM_TWIPS = 6 MM_ISOTROPIC = 7 MM_ANISOTROPIC = 8 MM_MIN = MM_TEXT MM_MAX = MM_ANISOTROPIC MM_MAX_FIXEDSCALE = MM_TWIPS ABSOLUTE = 1 RELATIVE = 2 WHITE_BRUSH = 0 LTGRAY_BRUSH = 1 GRAY_BRUSH = 2 DKGRAY_BRUSH = 3 BLACK_BRUSH = 4 NULL_BRUSH = 5 HOLLOW_BRUSH = NULL_BRUSH WHITE_PEN = 6 BLACK_PEN = 7 NULL_PEN = 8 OEM_FIXED_FONT = 10 ANSI_FIXED_FONT = 11 ANSI_VAR_FONT = 12 SYSTEM_FONT = 13 DEVICE_DEFAULT_FONT = 14 DEFAULT_PALETTE = 15 SYSTEM_FIXED_FONT = 16 STOCK_LAST = 16 CLR_INVALID = -1 # Exception/Status codes from winuser.h and winnt.h STATUS_WAIT_0 = 0 STATUS_ABANDONED_WAIT_0 = 128 STATUS_USER_APC = 192 STATUS_TIMEOUT = 258 STATUS_PENDING = 259 STATUS_SEGMENT_NOTIFICATION = 1073741829 STATUS_GUARD_PAGE_VIOLATION = -2147483647 STATUS_DATATYPE_MISALIGNMENT = -2147483646 STATUS_BREAKPOINT = -2147483645 STATUS_SINGLE_STEP = -2147483644 STATUS_ACCESS_VIOLATION = -1073741819 STATUS_IN_PAGE_ERROR = -1073741818 STATUS_INVALID_HANDLE = -1073741816 STATUS_NO_MEMORY = -1073741801 STATUS_ILLEGAL_INSTRUCTION = -1073741795 STATUS_NONCONTINUABLE_EXCEPTION = -1073741787 STATUS_INVALID_DISPOSITION = -1073741786 STATUS_ARRAY_BOUNDS_EXCEEDED = -1073741684 STATUS_FLOAT_DENORMAL_OPERAND = -1073741683 STATUS_FLOAT_DIVIDE_BY_ZERO = -1073741682 STATUS_FLOAT_INEXACT_RESULT = -1073741681 STATUS_FLOAT_INVALID_OPERATION = -1073741680 STATUS_FLOAT_OVERFLOW = -1073741679 STATUS_FLOAT_STACK_CHECK = -1073741678 STATUS_FLOAT_UNDERFLOW = -1073741677 STATUS_INTEGER_DIVIDE_BY_ZERO = -1073741676 STATUS_INTEGER_OVERFLOW = -1073741675 STATUS_PRIVILEGED_INSTRUCTION = -1073741674 STATUS_STACK_OVERFLOW = -1073741571 STATUS_CONTROL_C_EXIT = -1073741510 WAIT_FAILED = -1 WAIT_OBJECT_0 = STATUS_WAIT_0 + 0 WAIT_ABANDONED = STATUS_ABANDONED_WAIT_0 + 0 WAIT_ABANDONED_0 = STATUS_ABANDONED_WAIT_0 + 0 WAIT_TIMEOUT = STATUS_TIMEOUT WAIT_IO_COMPLETION = STATUS_USER_APC STILL_ACTIVE = STATUS_PENDING EXCEPTION_ACCESS_VIOLATION = STATUS_ACCESS_VIOLATION EXCEPTION_DATATYPE_MISALIGNMENT = STATUS_DATATYPE_MISALIGNMENT EXCEPTION_BREAKPOINT = STATUS_BREAKPOINT EXCEPTION_SINGLE_STEP = STATUS_SINGLE_STEP EXCEPTION_ARRAY_BOUNDS_EXCEEDED = STATUS_ARRAY_BOUNDS_EXCEEDED EXCEPTION_FLT_DENORMAL_OPERAND = STATUS_FLOAT_DENORMAL_OPERAND EXCEPTION_FLT_DIVIDE_BY_ZERO = STATUS_FLOAT_DIVIDE_BY_ZERO EXCEPTION_FLT_INEXACT_RESULT = STATUS_FLOAT_INEXACT_RESULT EXCEPTION_FLT_INVALID_OPERATION = STATUS_FLOAT_INVALID_OPERATION EXCEPTION_FLT_OVERFLOW = STATUS_FLOAT_OVERFLOW EXCEPTION_FLT_STACK_CHECK = STATUS_FLOAT_STACK_CHECK EXCEPTION_FLT_UNDERFLOW = STATUS_FLOAT_UNDERFLOW EXCEPTION_INT_DIVIDE_BY_ZERO = STATUS_INTEGER_DIVIDE_BY_ZERO EXCEPTION_INT_OVERFLOW = STATUS_INTEGER_OVERFLOW EXCEPTION_PRIV_INSTRUCTION = STATUS_PRIVILEGED_INSTRUCTION EXCEPTION_IN_PAGE_ERROR = STATUS_IN_PAGE_ERROR EXCEPTION_ILLEGAL_INSTRUCTION = STATUS_ILLEGAL_INSTRUCTION EXCEPTION_NONCONTINUABLE_EXCEPTION = STATUS_NONCONTINUABLE_EXCEPTION EXCEPTION_STACK_OVERFLOW = STATUS_STACK_OVERFLOW EXCEPTION_INVALID_DISPOSITION = STATUS_INVALID_DISPOSITION EXCEPTION_GUARD_PAGE = STATUS_GUARD_PAGE_VIOLATION EXCEPTION_INVALID_HANDLE = STATUS_INVALID_HANDLE CONTROL_C_EXIT = STATUS_CONTROL_C_EXIT # winuser.h line 8594 # constants used with SystemParametersInfo SPI_GETBEEP = 1 SPI_SETBEEP = 2 SPI_GETMOUSE = 3 SPI_SETMOUSE = 4 SPI_GETBORDER = 5 SPI_SETBORDER = 6 SPI_GETKEYBOARDSPEED = 10 SPI_SETKEYBOARDSPEED = 11 SPI_LANGDRIVER = 12 SPI_ICONHORIZONTALSPACING = 13 SPI_GETSCREENSAVETIMEOUT = 14 SPI_SETSCREENSAVETIMEOUT = 15 SPI_GETSCREENSAVEACTIVE = 16 SPI_SETSCREENSAVEACTIVE = 17 SPI_GETGRIDGRANULARITY = 18 SPI_SETGRIDGRANULARITY = 19 SPI_SETDESKWALLPAPER = 20 SPI_SETDESKPATTERN = 21 SPI_GETKEYBOARDDELAY = 22 SPI_SETKEYBOARDDELAY = 23 SPI_ICONVERTICALSPACING = 24 SPI_GETICONTITLEWRAP = 25 SPI_SETICONTITLEWRAP = 26 SPI_GETMENUDROPALIGNMENT = 27 SPI_SETMENUDROPALIGNMENT = 28 SPI_SETDOUBLECLKWIDTH = 29 SPI_SETDOUBLECLKHEIGHT = 30 SPI_GETICONTITLELOGFONT = 31 SPI_SETDOUBLECLICKTIME = 32 SPI_SETMOUSEBUTTONSWAP = 33 SPI_SETICONTITLELOGFONT = 34 SPI_GETFASTTASKSWITCH = 35 SPI_SETFASTTASKSWITCH = 36 SPI_SETDRAGFULLWINDOWS = 37 SPI_GETDRAGFULLWINDOWS = 38 SPI_GETNONCLIENTMETRICS = 41 SPI_SETNONCLIENTMETRICS = 42 SPI_GETMINIMIZEDMETRICS = 43 SPI_SETMINIMIZEDMETRICS = 44 SPI_GETICONMETRICS = 45 SPI_SETICONMETRICS = 46 SPI_SETWORKAREA = 47 SPI_GETWORKAREA = 48 SPI_SETPENWINDOWS = 49 SPI_GETFILTERKEYS = 50 SPI_SETFILTERKEYS = 51 SPI_GETTOGGLEKEYS = 52 SPI_SETTOGGLEKEYS = 53 SPI_GETMOUSEKEYS = 54 SPI_SETMOUSEKEYS = 55 SPI_GETSHOWSOUNDS = 56 SPI_SETSHOWSOUNDS = 57 SPI_GETSTICKYKEYS = 58 SPI_SETSTICKYKEYS = 59 SPI_GETACCESSTIMEOUT = 60 SPI_SETACCESSTIMEOUT = 61 SPI_GETSERIALKEYS = 62 SPI_SETSERIALKEYS = 63 SPI_GETSOUNDSENTRY = 64 SPI_SETSOUNDSENTRY = 65 SPI_GETHIGHCONTRAST = 66 SPI_SETHIGHCONTRAST = 67 SPI_GETKEYBOARDPREF = 68 SPI_SETKEYBOARDPREF = 69 SPI_GETSCREENREADER = 70 SPI_SETSCREENREADER = 71 SPI_GETANIMATION = 72 SPI_SETANIMATION = 73 SPI_GETFONTSMOOTHING = 74 SPI_SETFONTSMOOTHING = 75 SPI_SETDRAGWIDTH = 76 SPI_SETDRAGHEIGHT = 77 SPI_SETHANDHELD = 78 SPI_GETLOWPOWERTIMEOUT = 79 SPI_GETPOWEROFFTIMEOUT = 80 SPI_SETLOWPOWERTIMEOUT = 81 SPI_SETPOWEROFFTIMEOUT = 82 SPI_GETLOWPOWERACTIVE = 83 SPI_GETPOWEROFFACTIVE = 84 SPI_SETLOWPOWERACTIVE = 85 SPI_SETPOWEROFFACTIVE = 86 SPI_SETCURSORS = 87 SPI_SETICONS = 88 SPI_GETDEFAULTINPUTLANG = 89 SPI_SETDEFAULTINPUTLANG = 90 SPI_SETLANGTOGGLE = 91 SPI_GETWINDOWSEXTENSION = 92 SPI_SETMOUSETRAILS = 93 SPI_GETMOUSETRAILS = 94 SPI_GETSNAPTODEFBUTTON = 95 SPI_SETSNAPTODEFBUTTON = 96 SPI_SETSCREENSAVERRUNNING = 97 SPI_SCREENSAVERRUNNING = SPI_SETSCREENSAVERRUNNING SPI_GETMOUSEHOVERWIDTH = 98 SPI_SETMOUSEHOVERWIDTH = 99 SPI_GETMOUSEHOVERHEIGHT = 100 SPI_SETMOUSEHOVERHEIGHT = 101 SPI_GETMOUSEHOVERTIME = 102 SPI_SETMOUSEHOVERTIME = 103 SPI_GETWHEELSCROLLLINES = 104 SPI_SETWHEELSCROLLLINES = 105 SPI_GETMENUSHOWDELAY = 106 SPI_SETMENUSHOWDELAY = 107 SPI_GETSHOWIMEUI = 110 SPI_SETSHOWIMEUI = 111 SPI_GETMOUSESPEED = 112 SPI_SETMOUSESPEED = 113 SPI_GETSCREENSAVERRUNNING = 114 SPI_GETDESKWALLPAPER = 115 SPI_GETACTIVEWINDOWTRACKING = 4096 SPI_SETACTIVEWINDOWTRACKING = 4097 SPI_GETMENUANIMATION = 4098 SPI_SETMENUANIMATION = 4099 SPI_GETCOMBOBOXANIMATION = 4100 SPI_SETCOMBOBOXANIMATION = 4101 SPI_GETLISTBOXSMOOTHSCROLLING = 4102 SPI_SETLISTBOXSMOOTHSCROLLING = 4103 SPI_GETGRADIENTCAPTIONS = 4104 SPI_SETGRADIENTCAPTIONS = 4105 SPI_GETKEYBOARDCUES = 4106 SPI_SETKEYBOARDCUES = 4107 SPI_GETMENUUNDERLINES = 4106 SPI_SETMENUUNDERLINES = 4107 SPI_GETACTIVEWNDTRKZORDER = 4108 SPI_SETACTIVEWNDTRKZORDER = 4109 SPI_GETHOTTRACKING = 4110 SPI_SETHOTTRACKING = 4111 SPI_GETMENUFADE = 4114 SPI_SETMENUFADE = 4115 SPI_GETSELECTIONFADE = 4116 SPI_SETSELECTIONFADE = 4117 SPI_GETTOOLTIPANIMATION = 4118 SPI_SETTOOLTIPANIMATION = 4119 SPI_GETTOOLTIPFADE = 4120 SPI_SETTOOLTIPFADE = 4121 SPI_GETCURSORSHADOW = 4122 SPI_SETCURSORSHADOW = 4123 SPI_GETMOUSESONAR = 4124 SPI_SETMOUSESONAR = 4125 SPI_GETMOUSECLICKLOCK = 4126 SPI_SETMOUSECLICKLOCK = 4127 SPI_GETMOUSEVANISH = 4128 SPI_SETMOUSEVANISH = 4129 SPI_GETFLATMENU = 4130 SPI_SETFLATMENU = 4131 SPI_GETDROPSHADOW = 4132 SPI_SETDROPSHADOW = 4133 SPI_GETBLOCKSENDINPUTRESETS = 4134 SPI_SETBLOCKSENDINPUTRESETS = 4135 SPI_GETUIEFFECTS = 4158 SPI_SETUIEFFECTS = 4159 SPI_GETFOREGROUNDLOCKTIMEOUT = 8192 SPI_SETFOREGROUNDLOCKTIMEOUT = 8193 SPI_GETACTIVEWNDTRKTIMEOUT = 8194 SPI_SETACTIVEWNDTRKTIMEOUT = 8195 SPI_GETFOREGROUNDFLASHCOUNT = 8196 SPI_SETFOREGROUNDFLASHCOUNT = 8197 SPI_GETCARETWIDTH = 8198 SPI_SETCARETWIDTH = 8199 SPI_GETMOUSECLICKLOCKTIME = 8200 SPI_SETMOUSECLICKLOCKTIME = 8201 SPI_GETFONTSMOOTHINGTYPE = 8202 SPI_SETFONTSMOOTHINGTYPE = 8203 SPI_GETFONTSMOOTHINGCONTRAST = 8204 SPI_SETFONTSMOOTHINGCONTRAST = 8205 SPI_GETFOCUSBORDERWIDTH = 8206 SPI_SETFOCUSBORDERWIDTH = 8207 SPI_GETFOCUSBORDERHEIGHT = 8208 SPI_SETFOCUSBORDERHEIGHT = 8209 SPI_GETFONTSMOOTHINGORIENTATION = 8210 SPI_SETFONTSMOOTHINGORIENTATION = 8211 # fWinIni flags for SystemParametersInfo SPIF_UPDATEINIFILE = 1 SPIF_SENDWININICHANGE = 2 SPIF_SENDCHANGE = SPIF_SENDWININICHANGE # used with SystemParametersInfo and SPI_GETFONTSMOOTHINGTYPE/SPI_SETFONTSMOOTHINGTYPE FE_FONTSMOOTHINGSTANDARD = 1 FE_FONTSMOOTHINGCLEARTYPE = 2 FE_FONTSMOOTHINGDOCKING = 32768 METRICS_USEDEFAULT = -1 ARW_BOTTOMLEFT = 0 ARW_BOTTOMRIGHT = 1 ARW_TOPLEFT = 2 ARW_TOPRIGHT = 3 ARW_STARTMASK = 3 ARW_STARTRIGHT = 1 ARW_STARTTOP = 2 ARW_LEFT = 0 ARW_RIGHT = 0 ARW_UP = 4 ARW_DOWN = 4 ARW_HIDE = 8 #ARW_VALID = 0x000F SERKF_SERIALKEYSON = 1 SERKF_AVAILABLE = 2 SERKF_INDICATOR = 4 HCF_HIGHCONTRASTON = 1 HCF_AVAILABLE = 2 HCF_HOTKEYACTIVE = 4 HCF_CONFIRMHOTKEY = 8 HCF_HOTKEYSOUND = 16 HCF_INDICATOR = 32 HCF_HOTKEYAVAILABLE = 64 CDS_UPDATEREGISTRY = 1 CDS_TEST = 2 CDS_FULLSCREEN = 4 CDS_GLOBAL = 8 CDS_SET_PRIMARY = 16 CDS_RESET = 1073741824 CDS_SETRECT = 536870912 CDS_NORESET = 268435456 # return values from ChangeDisplaySettings and ChangeDisplaySettingsEx DISP_CHANGE_SUCCESSFUL = 0 DISP_CHANGE_RESTART = 1 DISP_CHANGE_FAILED = -1 DISP_CHANGE_BADMODE = -2 DISP_CHANGE_NOTUPDATED = -3 DISP_CHANGE_BADFLAGS = -4 DISP_CHANGE_BADPARAM = -5 DISP_CHANGE_BADDUALVIEW = -6 ENUM_CURRENT_SETTINGS = -1 ENUM_REGISTRY_SETTINGS = -2 FKF_FILTERKEYSON = 1 FKF_AVAILABLE = 2 FKF_HOTKEYACTIVE = 4 FKF_CONFIRMHOTKEY = 8 FKF_HOTKEYSOUND = 16 FKF_INDICATOR = 32 FKF_CLICKON = 64 SKF_STICKYKEYSON = 1 SKF_AVAILABLE = 2 SKF_HOTKEYACTIVE = 4 SKF_CONFIRMHOTKEY = 8 SKF_HOTKEYSOUND = 16 SKF_INDICATOR = 32 SKF_AUDIBLEFEEDBACK = 64 SKF_TRISTATE = 128 SKF_TWOKEYSOFF = 256 SKF_LALTLATCHED = 268435456 SKF_LCTLLATCHED = 67108864 SKF_LSHIFTLATCHED = 16777216 SKF_RALTLATCHED = 536870912 SKF_RCTLLATCHED = 134217728 SKF_RSHIFTLATCHED = 33554432 SKF_LWINLATCHED = 1073741824 SKF_RWINLATCHED = -2147483648 SKF_LALTLOCKED = 1048576 SKF_LCTLLOCKED = 262144 SKF_LSHIFTLOCKED = 65536 SKF_RALTLOCKED = 2097152 SKF_RCTLLOCKED = 524288 SKF_RSHIFTLOCKED = 131072 SKF_LWINLOCKED = 4194304 SKF_RWINLOCKED = 8388608 MKF_MOUSEKEYSON = 1 MKF_AVAILABLE = 2 MKF_HOTKEYACTIVE = 4 MKF_CONFIRMHOTKEY = 8 MKF_HOTKEYSOUND = 16 MKF_INDICATOR = 32 MKF_MODIFIERS = 64 MKF_REPLACENUMBERS = 128 MKF_LEFTBUTTONSEL = 268435456 MKF_RIGHTBUTTONSEL = 536870912 MKF_LEFTBUTTONDOWN = 16777216 MKF_RIGHTBUTTONDOWN = 33554432 MKF_MOUSEMODE = -2147483648 ATF_TIMEOUTON = 1 ATF_ONOFFFEEDBACK = 2 SSGF_NONE = 0 SSGF_DISPLAY = 3 SSTF_NONE = 0 SSTF_CHARS = 1 SSTF_BORDER = 2 SSTF_DISPLAY = 3 SSWF_NONE = 0 SSWF_TITLE = 1 SSWF_WINDOW = 2 SSWF_DISPLAY = 3 SSWF_CUSTOM = 4 SSF_SOUNDSENTRYON = 1 SSF_AVAILABLE = 2 SSF_INDICATOR = 4 TKF_TOGGLEKEYSON = 1 TKF_AVAILABLE = 2 TKF_HOTKEYACTIVE = 4 TKF_CONFIRMHOTKEY = 8 TKF_HOTKEYSOUND = 16 TKF_INDICATOR = 32 SLE_ERROR = 1 SLE_MINORERROR = 2 SLE_WARNING = 3 MONITOR_DEFAULTTONULL = 0 MONITOR_DEFAULTTOPRIMARY = 1 MONITOR_DEFAULTTONEAREST = 2 MONITORINFOF_PRIMARY = 1 CCHDEVICENAME = 32 CHILDID_SELF = 0 INDEXID_OBJECT = 0 INDEXID_CONTAINER = 0 OBJID_WINDOW = 0 OBJID_SYSMENU = -1 OBJID_TITLEBAR = -2 OBJID_MENU = -3 OBJID_CLIENT = -4 OBJID_VSCROLL = -5 OBJID_HSCROLL = -6 OBJID_SIZEGRIP = -7 OBJID_CARET = -8 OBJID_CURSOR = -9 OBJID_ALERT = -10 OBJID_SOUND = -11 EVENT_MIN = 1 EVENT_MAX = 2147483647 EVENT_SYSTEM_SOUND = 1 EVENT_SYSTEM_ALERT = 2 EVENT_SYSTEM_FOREGROUND = 3 EVENT_SYSTEM_MENUSTART = 4 EVENT_SYSTEM_MENUEND = 5 EVENT_SYSTEM_MENUPOPUPSTART = 6 EVENT_SYSTEM_MENUPOPUPEND = 7 EVENT_SYSTEM_CAPTURESTART = 8 EVENT_SYSTEM_CAPTUREEND = 9 EVENT_SYSTEM_MOVESIZESTART = 10 EVENT_SYSTEM_MOVESIZEEND = 11 EVENT_SYSTEM_CONTEXTHELPSTART = 12 EVENT_SYSTEM_CONTEXTHELPEND = 13 EVENT_SYSTEM_DRAGDROPSTART = 14 EVENT_SYSTEM_DRAGDROPEND = 15 EVENT_SYSTEM_DIALOGSTART = 16 EVENT_SYSTEM_DIALOGEND = 17 EVENT_SYSTEM_SCROLLINGSTART = 18 EVENT_SYSTEM_SCROLLINGEND = 19 EVENT_SYSTEM_SWITCHSTART = 20 EVENT_SYSTEM_SWITCHEND = 21 EVENT_SYSTEM_MINIMIZESTART = 22 EVENT_SYSTEM_MINIMIZEEND = 23 EVENT_OBJECT_CREATE = 32768 EVENT_OBJECT_DESTROY = 32769 EVENT_OBJECT_SHOW = 32770 EVENT_OBJECT_HIDE = 32771 EVENT_OBJECT_REORDER = 32772 EVENT_OBJECT_FOCUS = 32773 EVENT_OBJECT_SELECTION = 32774 EVENT_OBJECT_SELECTIONADD = 32775 EVENT_OBJECT_SELECTIONREMOVE = 32776 EVENT_OBJECT_SELECTIONWITHIN = 32777 EVENT_OBJECT_STATECHANGE = 32778 EVENT_OBJECT_LOCATIONCHANGE = 32779 EVENT_OBJECT_NAMECHANGE = 32780 EVENT_OBJECT_DESCRIPTIONCHANGE = 32781 EVENT_OBJECT_VALUECHANGE = 32782 EVENT_OBJECT_PARENTCHANGE = 32783 EVENT_OBJECT_HELPCHANGE = 32784 EVENT_OBJECT_DEFACTIONCHANGE = 32785 EVENT_OBJECT_ACCELERATORCHANGE = 32786 SOUND_SYSTEM_STARTUP = 1 SOUND_SYSTEM_SHUTDOWN = 2 SOUND_SYSTEM_BEEP = 3 SOUND_SYSTEM_ERROR = 4 SOUND_SYSTEM_QUESTION = 5 SOUND_SYSTEM_WARNING = 6 SOUND_SYSTEM_INFORMATION = 7 SOUND_SYSTEM_MAXIMIZE = 8 SOUND_SYSTEM_MINIMIZE = 9 SOUND_SYSTEM_RESTOREUP = 10 SOUND_SYSTEM_RESTOREDOWN = 11 SOUND_SYSTEM_APPSTART = 12 SOUND_SYSTEM_FAULT = 13 SOUND_SYSTEM_APPEND = 14 SOUND_SYSTEM_MENUCOMMAND = 15 SOUND_SYSTEM_MENUPOPUP = 16 CSOUND_SYSTEM = 16 ALERT_SYSTEM_INFORMATIONAL = 1 ALERT_SYSTEM_WARNING = 2 ALERT_SYSTEM_ERROR = 3 ALERT_SYSTEM_QUERY = 4 ALERT_SYSTEM_CRITICAL = 5 CALERT_SYSTEM = 6 WINEVENT_OUTOFCONTEXT = 0 WINEVENT_SKIPOWNTHREAD = 1 WINEVENT_SKIPOWNPROCESS = 2 WINEVENT_INCONTEXT = 4 GUI_CARETBLINKING = 1 GUI_INMOVESIZE = 2 GUI_INMENUMODE = 4 GUI_SYSTEMMENUMODE = 8 GUI_POPUPMENUMODE = 16 STATE_SYSTEM_UNAVAILABLE = 1 STATE_SYSTEM_SELECTED = 2 STATE_SYSTEM_FOCUSED = 4 STATE_SYSTEM_PRESSED = 8 STATE_SYSTEM_CHECKED = 16 STATE_SYSTEM_MIXED = 32 STATE_SYSTEM_READONLY = 64 STATE_SYSTEM_HOTTRACKED = 128 STATE_SYSTEM_DEFAULT = 256 STATE_SYSTEM_EXPANDED = 512 STATE_SYSTEM_COLLAPSED = 1024 STATE_SYSTEM_BUSY = 2048 STATE_SYSTEM_FLOATING = 4096 STATE_SYSTEM_MARQUEED = 8192 STATE_SYSTEM_ANIMATED = 16384 STATE_SYSTEM_INVISIBLE = 32768 STATE_SYSTEM_OFFSCREEN = 65536 STATE_SYSTEM_SIZEABLE = 131072 STATE_SYSTEM_MOVEABLE = 262144 STATE_SYSTEM_SELFVOICING = 524288 STATE_SYSTEM_FOCUSABLE = 1048576 STATE_SYSTEM_SELECTABLE = 2097152 STATE_SYSTEM_LINKED = 4194304 STATE_SYSTEM_TRAVERSED = 8388608 STATE_SYSTEM_MULTISELECTABLE = 16777216 STATE_SYSTEM_EXTSELECTABLE = 33554432 STATE_SYSTEM_ALERT_LOW = 67108864 STATE_SYSTEM_ALERT_MEDIUM = 134217728 STATE_SYSTEM_ALERT_HIGH = 268435456 STATE_SYSTEM_VALID = 536870911 CCHILDREN_TITLEBAR = 5 CCHILDREN_SCROLLBAR = 5 CURSOR_SHOWING = 1 WS_ACTIVECAPTION = 1 GA_MIC = 1 GA_PARENT = 1 GA_ROOT = 2 GA_ROOTOWNER = 3 GA_MAC = 4 # winuser.h line 1979 BF_LEFT = 1 BF_TOP = 2 BF_RIGHT = 4 BF_BOTTOM = 8 BF_TOPLEFT = (BF_TOP | BF_LEFT) BF_TOPRIGHT = (BF_TOP | BF_RIGHT) BF_BOTTOMLEFT = (BF_BOTTOM | BF_LEFT) BF_BOTTOMRIGHT = (BF_BOTTOM | BF_RIGHT) BF_RECT = (BF_LEFT | BF_TOP | BF_RIGHT | BF_BOTTOM) BF_DIAGONAL = 16 BF_DIAGONAL_ENDTOPRIGHT = (BF_DIAGONAL | BF_TOP | BF_RIGHT) BF_DIAGONAL_ENDTOPLEFT = (BF_DIAGONAL | BF_TOP | BF_LEFT) BF_DIAGONAL_ENDBOTTOMLEFT = (BF_DIAGONAL | BF_BOTTOM | BF_LEFT) BF_DIAGONAL_ENDBOTTOMRIGHT = (BF_DIAGONAL | BF_BOTTOM | BF_RIGHT) BF_MIDDLE = 2048 BF_SOFT = 4096 BF_ADJUST = 8192 BF_FLAT = 16384 BF_MONO = 32768 DFC_CAPTION = 1 DFC_MENU = 2 DFC_SCROLL = 3 DFC_BUTTON = 4 DFC_POPUPMENU = 5 DFCS_CAPTIONCLOSE = 0 DFCS_CAPTIONMIN = 1 DFCS_CAPTIONMAX = 2 DFCS_CAPTIONRESTORE = 3 DFCS_CAPTIONHELP = 4 DFCS_MENUARROW = 0 DFCS_MENUCHECK = 1 DFCS_MENUBULLET = 2 DFCS_MENUARROWRIGHT = 4 DFCS_SCROLLUP = 0 DFCS_SCROLLDOWN = 1 DFCS_SCROLLLEFT = 2 DFCS_SCROLLRIGHT = 3 DFCS_SCROLLCOMBOBOX = 5 DFCS_SCROLLSIZEGRIP = 8 DFCS_SCROLLSIZEGRIPRIGHT = 16 DFCS_BUTTONCHECK = 0 DFCS_BUTTONRADIOIMAGE = 1 DFCS_BUTTONRADIOMASK = 2 DFCS_BUTTONRADIO = 4 DFCS_BUTTON3STATE = 8 DFCS_BUTTONPUSH = 16 DFCS_INACTIVE = 256 DFCS_PUSHED = 512 DFCS_CHECKED = 1024 DFCS_TRANSPARENT = 2048 DFCS_HOT = 4096 DFCS_ADJUSTRECT = 8192 DFCS_FLAT = 16384 DFCS_MONO = 32768 DC_ACTIVE = 1 DC_SMALLCAP = 2 DC_ICON = 4 DC_TEXT = 8 DC_INBUTTON = 16 DC_GRADIENT = 32 IDANI_OPEN = 1 IDANI_CLOSE = 2 IDANI_CAPTION = 3 CF_TEXT = 1 CF_BITMAP = 2 CF_METAFILEPICT = 3 CF_SYLK = 4 CF_DIF = 5 CF_TIFF = 6 CF_OEMTEXT = 7 CF_DIB = 8 CF_PALETTE = 9 CF_PENDATA = 10 CF_RIFF = 11 CF_WAVE = 12 CF_UNICODETEXT = 13 CF_ENHMETAFILE = 14 CF_HDROP = 15 CF_LOCALE = 16 CF_MAX = 17 CF_OWNERDISPLAY = 128 CF_DSPTEXT = 129 CF_DSPBITMAP = 130 CF_DSPMETAFILEPICT = 131 CF_DSPENHMETAFILE = 142 CF_PRIVATEFIRST = 512 CF_PRIVATELAST = 767 CF_GDIOBJFIRST = 768 CF_GDIOBJLAST = 1023 FVIRTKEY =1 FNOINVERT = 2 FSHIFT = 4 FCONTROL = 8 FALT = 16 WPF_SETMINPOSITION = 1 WPF_RESTORETOMAXIMIZED = 2 ODT_MENU = 1 ODT_LISTBOX = 2 ODT_COMBOBOX = 3 ODT_BUTTON = 4 ODT_STATIC = 5 ODA_DRAWENTIRE = 1 ODA_SELECT = 2 ODA_FOCUS = 4 ODS_SELECTED = 1 ODS_GRAYED = 2 ODS_DISABLED = 4 ODS_CHECKED = 8 ODS_FOCUS = 16 ODS_DEFAULT = 32 ODS_COMBOBOXEDIT = 4096 ODS_HOTLIGHT = 64 ODS_INACTIVE = 128 PM_NOREMOVE = 0 PM_REMOVE = 1 PM_NOYIELD = 2 # Name clashes with key.MOD_ALT, key.MOD_CONTROL and key.MOD_SHIFT WIN32_MOD_ALT = 1 WIN32_MOD_CONTROL = 2 WIN32_MOD_SHIFT = 4 WIN32_MOD_WIN = 8 IDHOT_SNAPWINDOW = (-1) IDHOT_SNAPDESKTOP = (-2) #EW_RESTARTWINDOWS = 0x0042 #EW_REBOOTSYSTEM = 0x0043 #EW_EXITANDEXECAPP = 0x0044 ENDSESSION_LOGOFF = -2147483648 EWX_LOGOFF = 0 EWX_SHUTDOWN = 1 EWX_REBOOT = 2 EWX_FORCE = 4 EWX_POWEROFF = 8 EWX_FORCEIFHUNG = 16 BSM_ALLCOMPONENTS = 0 BSM_VXDS = 1 BSM_NETDRIVER = 2 BSM_INSTALLABLEDRIVERS = 4 BSM_APPLICATIONS = 8 BSM_ALLDESKTOPS = 16 BSF_QUERY = 1 BSF_IGNORECURRENTTASK = 2 BSF_FLUSHDISK = 4 BSF_NOHANG = 8 BSF_POSTMESSAGE = 16 BSF_FORCEIFHUNG = 32 BSF_NOTIMEOUTIFNOTHUNG = 64 BROADCAST_QUERY_DENY = 1112363332 # Return this value to deny a query. DBWF_LPARAMPOINTER = 32768 # winuser.h line 3232 SWP_NOSIZE = 1 SWP_NOMOVE = 2 SWP_NOZORDER = 4 SWP_NOREDRAW = 8 SWP_NOACTIVATE = 16 SWP_FRAMECHANGED = 32 SWP_SHOWWINDOW = 64 SWP_HIDEWINDOW = 128 SWP_NOCOPYBITS = 256 SWP_NOOWNERZORDER = 512 SWP_NOSENDCHANGING = 1024 SWP_DRAWFRAME = SWP_FRAMECHANGED SWP_NOREPOSITION = SWP_NOOWNERZORDER SWP_DEFERERASE = 8192 SWP_ASYNCWINDOWPOS = 16384 DLGWINDOWEXTRA = 30 # winuser.h line 4249 KEYEVENTF_EXTENDEDKEY = 1 KEYEVENTF_KEYUP = 2 MOUSEEVENTF_MOVE = 1 MOUSEEVENTF_LEFTDOWN = 2 MOUSEEVENTF_LEFTUP = 4 MOUSEEVENTF_RIGHTDOWN = 8 MOUSEEVENTF_RIGHTUP = 16 MOUSEEVENTF_MIDDLEDOWN = 32 MOUSEEVENTF_MIDDLEUP = 64 MOUSEEVENTF_ABSOLUTE = 32768 INPUT_MOUSE = 0 INPUT_KEYBOARD = 1 INPUT_HARDWARE = 2 MWMO_WAITALL = 1 MWMO_ALERTABLE = 2 MWMO_INPUTAVAILABLE = 4 QS_KEY = 1 QS_MOUSEMOVE = 2 QS_MOUSEBUTTON = 4 QS_POSTMESSAGE = 8 QS_TIMER = 16 QS_PAINT = 32 QS_SENDMESSAGE = 64 QS_HOTKEY = 128 QS_MOUSE = (QS_MOUSEMOVE | \ QS_MOUSEBUTTON) QS_INPUT = (QS_MOUSE | \ QS_KEY) QS_ALLEVENTS = (QS_INPUT | \ QS_POSTMESSAGE | \ QS_TIMER | \ QS_PAINT | \ QS_HOTKEY) QS_ALLINPUT = (QS_INPUT | \ QS_POSTMESSAGE | \ QS_TIMER | \ QS_PAINT | \ QS_HOTKEY | \ QS_SENDMESSAGE) IMN_CLOSESTATUSWINDOW = 1 IMN_OPENSTATUSWINDOW = 2 IMN_CHANGECANDIDATE = 3 IMN_CLOSECANDIDATE = 4 IMN_OPENCANDIDATE = 5 IMN_SETCONVERSIONMODE = 6 IMN_SETSENTENCEMODE = 7 IMN_SETOPENSTATUS = 8 IMN_SETCANDIDATEPOS = 9 IMN_SETCOMPOSITIONFONT = 10 IMN_SETCOMPOSITIONWINDOW = 11 IMN_SETSTATUSWINDOWPOS = 12 IMN_GUIDELINE = 13 IMN_PRIVATE = 14 # winuser.h line 8518 HELP_CONTEXT = 1 HELP_QUIT = 2 HELP_INDEX = 3 HELP_CONTENTS = 3 HELP_HELPONHELP = 4 HELP_SETINDEX = 5 HELP_SETCONTENTS = 5 HELP_CONTEXTPOPUP = 8 HELP_FORCEFILE = 9 HELP_KEY = 257 HELP_COMMAND = 258 HELP_PARTIALKEY = 261 HELP_MULTIKEY = 513 HELP_SETWINPOS = 515 HELP_CONTEXTMENU = 10 HELP_FINDER = 11 HELP_WM_HELP = 12 HELP_SETPOPUP_POS = 13 HELP_TCARD = 32768 HELP_TCARD_DATA = 16 HELP_TCARD_OTHER_CALLER = 17 IDH_NO_HELP = 28440 IDH_MISSING_CONTEXT = 28441 # Control doesn't have matching help context IDH_GENERIC_HELP_BUTTON = 28442 # Property sheet help button IDH_OK = 28443 IDH_CANCEL = 28444 IDH_HELP = 28445 GR_GDIOBJECTS = 0 # Count of GDI objects GR_USEROBJECTS = 1 # Count of USER objects # Generated by h2py from \msvcnt\include\wingdi.h # manually added (missed by generation some how! SRCCOPY = 13369376 # dest = source SRCPAINT = 15597702 # dest = source OR dest SRCAND = 8913094 # dest = source AND dest SRCINVERT = 6684742 # dest = source XOR dest SRCERASE = 4457256 # dest = source AND (NOT dest ) NOTSRCCOPY = 3342344 # dest = (NOT source) NOTSRCERASE = 1114278 # dest = (NOT src) AND (NOT dest) MERGECOPY = 12583114 # dest = (source AND pattern) MERGEPAINT = 12255782 # dest = (NOT source) OR dest PATCOPY = 15728673 # dest = pattern PATPAINT = 16452105 # dest = DPSnoo PATINVERT = 5898313 # dest = pattern XOR dest DSTINVERT = 5570569 # dest = (NOT dest) BLACKNESS = 66 # dest = BLACK WHITENESS = 16711778 # dest = WHITE # hacked and split manually by mhammond. R2_BLACK = 1 R2_NOTMERGEPEN = 2 R2_MASKNOTPEN = 3 R2_NOTCOPYPEN = 4 R2_MASKPENNOT = 5 R2_NOT = 6 R2_XORPEN = 7 R2_NOTMASKPEN = 8 R2_MASKPEN = 9 R2_NOTXORPEN = 10 R2_NOP = 11 R2_MERGENOTPEN = 12 R2_COPYPEN = 13 R2_MERGEPENNOT = 14 R2_MERGEPEN = 15 R2_WHITE = 16 R2_LAST = 16 GDI_ERROR = (-1) ERROR = 0 NULLREGION = 1 SIMPLEREGION = 2 COMPLEXREGION = 3 RGN_ERROR = ERROR RGN_AND = 1 RGN_OR = 2 RGN_XOR = 3 RGN_DIFF = 4 RGN_COPY = 5 RGN_MIN = RGN_AND RGN_MAX = RGN_COPY BLACKONWHITE = 1 WHITEONBLACK = 2 COLORONCOLOR = 3 HALFTONE = 4 MAXSTRETCHBLTMODE = 4 ALTERNATE = 1 WINDING = 2 POLYFILL_LAST = 2 TA_NOUPDATECP = 0 TA_UPDATECP = 1 TA_LEFT = 0 TA_RIGHT = 2 TA_CENTER = 6 TA_TOP = 0 TA_BOTTOM = 8 TA_BASELINE = 24 TA_MASK = (TA_BASELINE+TA_CENTER+TA_UPDATECP) VTA_BASELINE = TA_BASELINE VTA_LEFT = TA_BOTTOM VTA_RIGHT = TA_TOP VTA_CENTER = TA_CENTER VTA_BOTTOM = TA_RIGHT VTA_TOP = TA_LEFT ETO_GRAYED = 1 ETO_OPAQUE = 2 ETO_CLIPPED = 4 ASPECT_FILTERING = 1 DCB_RESET = 1 DCB_ACCUMULATE = 2 DCB_DIRTY = DCB_ACCUMULATE DCB_SET = (DCB_RESET | DCB_ACCUMULATE) DCB_ENABLE = 4 DCB_DISABLE = 8 META_SETBKCOLOR = 513 META_SETBKMODE = 258 META_SETMAPMODE = 259 META_SETROP2 = 260 META_SETRELABS = 261 META_SETPOLYFILLMODE = 262 META_SETSTRETCHBLTMODE = 263 META_SETTEXTCHAREXTRA = 264 META_SETTEXTCOLOR = 521 META_SETTEXTJUSTIFICATION = 522 META_SETWINDOWORG = 523 META_SETWINDOWEXT = 524 META_SETVIEWPORTORG = 525 META_SETVIEWPORTEXT = 526 META_OFFSETWINDOWORG = 527 META_SCALEWINDOWEXT = 1040 META_OFFSETVIEWPORTORG = 529 META_SCALEVIEWPORTEXT = 1042 META_LINETO = 531 META_MOVETO = 532 META_EXCLUDECLIPRECT = 1045 META_INTERSECTCLIPRECT = 1046 META_ARC = 2071 META_ELLIPSE = 1048 META_FLOODFILL = 1049 META_PIE = 2074 META_RECTANGLE = 1051 META_ROUNDRECT = 1564 META_PATBLT = 1565 META_SAVEDC = 30 META_SETPIXEL = 1055 META_OFFSETCLIPRGN = 544 META_TEXTOUT = 1313 META_BITBLT = 2338 META_STRETCHBLT = 2851 META_POLYGON = 804 META_POLYLINE = 805 META_ESCAPE = 1574 META_RESTOREDC = 295 META_FILLREGION = 552 META_FRAMEREGION = 1065 META_INVERTREGION = 298 META_PAINTREGION = 299 META_SELECTCLIPREGION = 300 META_SELECTOBJECT = 301 META_SETTEXTALIGN = 302 META_CHORD = 2096 META_SETMAPPERFLAGS = 561 META_EXTTEXTOUT = 2610 META_SETDIBTODEV = 3379 META_SELECTPALETTE = 564 META_REALIZEPALETTE = 53 META_ANIMATEPALETTE = 1078 META_SETPALENTRIES = 55 META_POLYPOLYGON = 1336 META_RESIZEPALETTE = 313 META_DIBBITBLT = 2368 META_DIBSTRETCHBLT = 2881 META_DIBCREATEPATTERNBRUSH = 322 META_STRETCHDIB = 3907 META_EXTFLOODFILL = 1352 META_DELETEOBJECT = 496 META_CREATEPALETTE = 247 META_CREATEPATTERNBRUSH = 505 META_CREATEPENINDIRECT = 762 META_CREATEFONTINDIRECT = 763 META_CREATEBRUSHINDIRECT = 764 META_CREATEREGION = 1791 FILE_BEGIN = 0 FILE_CURRENT = 1 FILE_END = 2 FILE_FLAG_WRITE_THROUGH = -2147483648 FILE_FLAG_OVERLAPPED = 1073741824 FILE_FLAG_NO_BUFFERING = 536870912 FILE_FLAG_RANDOM_ACCESS = 268435456 FILE_FLAG_SEQUENTIAL_SCAN = 134217728 FILE_FLAG_DELETE_ON_CLOSE = 67108864 FILE_FLAG_BACKUP_SEMANTICS = 33554432 FILE_FLAG_POSIX_SEMANTICS = 16777216 CREATE_NEW = 1 CREATE_ALWAYS = 2 OPEN_EXISTING = 3 OPEN_ALWAYS = 4 TRUNCATE_EXISTING = 5 PIPE_ACCESS_INBOUND = 1 PIPE_ACCESS_OUTBOUND = 2 PIPE_ACCESS_DUPLEX = 3 PIPE_CLIENT_END = 0 PIPE_SERVER_END = 1 PIPE_WAIT = 0 PIPE_NOWAIT = 1 PIPE_READMODE_BYTE = 0 PIPE_READMODE_MESSAGE = 2 PIPE_TYPE_BYTE = 0 PIPE_TYPE_MESSAGE = 4 PIPE_UNLIMITED_INSTANCES = 255 SECURITY_CONTEXT_TRACKING = 262144 SECURITY_EFFECTIVE_ONLY = 524288 SECURITY_SQOS_PRESENT = 1048576 SECURITY_VALID_SQOS_FLAGS = 2031616 DTR_CONTROL_DISABLE = 0 DTR_CONTROL_ENABLE = 1 DTR_CONTROL_HANDSHAKE = 2 RTS_CONTROL_DISABLE = 0 RTS_CONTROL_ENABLE = 1 RTS_CONTROL_HANDSHAKE = 2 RTS_CONTROL_TOGGLE = 3 GMEM_FIXED = 0 GMEM_MOVEABLE = 2 GMEM_NOCOMPACT = 16 GMEM_NODISCARD = 32 GMEM_ZEROINIT = 64 GMEM_MODIFY = 128 GMEM_DISCARDABLE = 256 GMEM_NOT_BANKED = 4096 GMEM_SHARE = 8192 GMEM_DDESHARE = 8192 GMEM_NOTIFY = 16384 GMEM_LOWER = GMEM_NOT_BANKED GMEM_VALID_FLAGS = 32626 GMEM_INVALID_HANDLE = 32768 GHND = (GMEM_MOVEABLE | GMEM_ZEROINIT) GPTR = (GMEM_FIXED | GMEM_ZEROINIT) GMEM_DISCARDED = 16384 GMEM_LOCKCOUNT = 255 LMEM_FIXED = 0 LMEM_MOVEABLE = 2 LMEM_NOCOMPACT = 16 LMEM_NODISCARD = 32 LMEM_ZEROINIT = 64 LMEM_MODIFY = 128 LMEM_DISCARDABLE = 3840 LMEM_VALID_FLAGS = 3954 LMEM_INVALID_HANDLE = 32768 LHND = (LMEM_MOVEABLE | LMEM_ZEROINIT) LPTR = (LMEM_FIXED | LMEM_ZEROINIT) NONZEROLHND = (LMEM_MOVEABLE) NONZEROLPTR = (LMEM_FIXED) LMEM_DISCARDED = 16384 LMEM_LOCKCOUNT = 255 DEBUG_PROCESS = 1 DEBUG_ONLY_THIS_PROCESS = 2 CREATE_SUSPENDED = 4 DETACHED_PROCESS = 8 CREATE_NEW_CONSOLE = 16 NORMAL_PRIORITY_CLASS = 32 IDLE_PRIORITY_CLASS = 64 HIGH_PRIORITY_CLASS = 128 REALTIME_PRIORITY_CLASS = 256 CREATE_NEW_PROCESS_GROUP = 512 CREATE_UNICODE_ENVIRONMENT = 1024 CREATE_SEPARATE_WOW_VDM = 2048 CREATE_SHARED_WOW_VDM = 4096 CREATE_DEFAULT_ERROR_MODE = 67108864 CREATE_NO_WINDOW = 134217728 PROFILE_USER = 268435456 PROFILE_KERNEL = 536870912 PROFILE_SERVER = 1073741824 THREAD_BASE_PRIORITY_LOWRT = 15 THREAD_BASE_PRIORITY_MAX = 2 THREAD_BASE_PRIORITY_MIN = -2 THREAD_BASE_PRIORITY_IDLE = -15 THREAD_PRIORITY_LOWEST = THREAD_BASE_PRIORITY_MIN THREAD_PRIORITY_BELOW_NORMAL = THREAD_PRIORITY_LOWEST+1 THREAD_PRIORITY_HIGHEST = THREAD_BASE_PRIORITY_MAX THREAD_PRIORITY_ABOVE_NORMAL = THREAD_PRIORITY_HIGHEST-1 THREAD_PRIORITY_ERROR_RETURN = MAXLONG THREAD_PRIORITY_TIME_CRITICAL = THREAD_BASE_PRIORITY_LOWRT THREAD_PRIORITY_IDLE = THREAD_BASE_PRIORITY_IDLE THREAD_PRIORITY_NORMAL = 0 EXCEPTION_DEBUG_EVENT = 1 CREATE_THREAD_DEBUG_EVENT = 2 CREATE_PROCESS_DEBUG_EVENT = 3 EXIT_THREAD_DEBUG_EVENT = 4 EXIT_PROCESS_DEBUG_EVENT = 5 LOAD_DLL_DEBUG_EVENT = 6 UNLOAD_DLL_DEBUG_EVENT = 7 OUTPUT_DEBUG_STRING_EVENT = 8 RIP_EVENT = 9 DRIVE_UNKNOWN = 0 DRIVE_NO_ROOT_DIR = 1 DRIVE_REMOVABLE = 2 DRIVE_FIXED = 3 DRIVE_REMOTE = 4 DRIVE_CDROM = 5 DRIVE_RAMDISK = 6 FILE_TYPE_UNKNOWN = 0 FILE_TYPE_DISK = 1 FILE_TYPE_CHAR = 2 FILE_TYPE_PIPE = 3 FILE_TYPE_REMOTE = 32768 NOPARITY = 0 ODDPARITY = 1 EVENPARITY = 2 MARKPARITY = 3 SPACEPARITY = 4 ONESTOPBIT = 0 ONE5STOPBITS = 1 TWOSTOPBITS = 2 CBR_110 = 110 CBR_300 = 300 CBR_600 = 600 CBR_1200 = 1200 CBR_2400 = 2400 CBR_4800 = 4800 CBR_9600 = 9600 CBR_14400 = 14400 CBR_19200 = 19200 CBR_38400 = 38400 CBR_56000 = 56000 CBR_57600 = 57600 CBR_115200 = 115200 CBR_128000 = 128000 CBR_256000 = 256000 S_QUEUEEMPTY = 0 S_THRESHOLD = 1 S_ALLTHRESHOLD = 2 S_NORMAL = 0 S_LEGATO = 1 S_STACCATO = 2 NMPWAIT_WAIT_FOREVER = -1 NMPWAIT_NOWAIT = 1 NMPWAIT_USE_DEFAULT_WAIT = 0 OF_READ = 0 OF_WRITE = 1 OF_READWRITE = 2 OF_SHARE_COMPAT = 0 OF_SHARE_EXCLUSIVE = 16 OF_SHARE_DENY_WRITE = 32 OF_SHARE_DENY_READ = 48 OF_SHARE_DENY_NONE = 64 OF_PARSE = 256 OF_DELETE = 512 OF_VERIFY = 1024 OF_CANCEL = 2048 OF_CREATE = 4096 OF_PROMPT = 8192 OF_EXIST = 16384 OF_REOPEN = 32768 OFS_MAXPATHNAME = 128 MAXINTATOM = 49152 # winbase.h PROCESS_HEAP_REGION = 1 PROCESS_HEAP_UNCOMMITTED_RANGE = 2 PROCESS_HEAP_ENTRY_BUSY = 4 PROCESS_HEAP_ENTRY_MOVEABLE = 16 PROCESS_HEAP_ENTRY_DDESHARE = 32 SCS_32BIT_BINARY = 0 SCS_DOS_BINARY = 1 SCS_WOW_BINARY = 2 SCS_PIF_BINARY = 3 SCS_POSIX_BINARY = 4 SCS_OS216_BINARY = 5 SEM_FAILCRITICALERRORS = 1 SEM_NOGPFAULTERRORBOX = 2 SEM_NOALIGNMENTFAULTEXCEPT = 4 SEM_NOOPENFILEERRORBOX = 32768 LOCKFILE_FAIL_IMMEDIATELY = 1 LOCKFILE_EXCLUSIVE_LOCK = 2 HANDLE_FLAG_INHERIT = 1 HANDLE_FLAG_PROTECT_FROM_CLOSE = 2 HINSTANCE_ERROR = 32 GET_TAPE_MEDIA_INFORMATION = 0 GET_TAPE_DRIVE_INFORMATION = 1 SET_TAPE_MEDIA_INFORMATION = 0 SET_TAPE_DRIVE_INFORMATION = 1 FORMAT_MESSAGE_ALLOCATE_BUFFER = 256 FORMAT_MESSAGE_IGNORE_INSERTS = 512 FORMAT_MESSAGE_FROM_STRING = 1024 FORMAT_MESSAGE_FROM_HMODULE = 2048 FORMAT_MESSAGE_FROM_SYSTEM = 4096 FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192 FORMAT_MESSAGE_MAX_WIDTH_MASK = 255 BACKUP_INVALID = 0 BACKUP_DATA = 1 BACKUP_EA_DATA = 2 BACKUP_SECURITY_DATA = 3 BACKUP_ALTERNATE_DATA = 4 BACKUP_LINK = 5 BACKUP_PROPERTY_DATA = 6 BACKUP_OBJECT_ID = 7 BACKUP_REPARSE_DATA = 8 BACKUP_SPARSE_BLOCK = 9 STREAM_NORMAL_ATTRIBUTE = 0 STREAM_MODIFIED_WHEN_READ = 1 STREAM_CONTAINS_SECURITY = 2 STREAM_CONTAINS_PROPERTIES = 4 STARTF_USESHOWWINDOW = 1 STARTF_USESIZE = 2 STARTF_USEPOSITION = 4 STARTF_USECOUNTCHARS = 8 STARTF_USEFILLATTRIBUTE = 16 STARTF_FORCEONFEEDBACK = 64 STARTF_FORCEOFFFEEDBACK = 128 STARTF_USESTDHANDLES = 256 STARTF_USEHOTKEY = 512 SHUTDOWN_NORETRY = 1 DONT_RESOLVE_DLL_REFERENCES = 1 LOAD_LIBRARY_AS_DATAFILE = 2 LOAD_WITH_ALTERED_SEARCH_PATH = 8 DDD_RAW_TARGET_PATH = 1 DDD_REMOVE_DEFINITION = 2 DDD_EXACT_MATCH_ON_REMOVE = 4 MOVEFILE_REPLACE_EXISTING = 1 MOVEFILE_COPY_ALLOWED = 2 MOVEFILE_DELAY_UNTIL_REBOOT = 4 MAX_COMPUTERNAME_LENGTH = 15 LOGON32_LOGON_INTERACTIVE = 2 LOGON32_LOGON_BATCH = 4 LOGON32_LOGON_SERVICE = 5 LOGON32_PROVIDER_DEFAULT = 0 LOGON32_PROVIDER_WINNT35 = 1 VER_PLATFORM_WIN32s = 0 VER_PLATFORM_WIN32_WINDOWS = 1 VER_PLATFORM_WIN32_NT = 2 TC_NORMAL = 0 TC_HARDERR = 1 TC_GP_TRAP = 2 TC_SIGNAL = 3 AC_LINE_OFFLINE = 0 AC_LINE_ONLINE = 1 AC_LINE_BACKUP_POWER = 2 AC_LINE_UNKNOWN = 255 BATTERY_FLAG_HIGH = 1 BATTERY_FLAG_LOW = 2 BATTERY_FLAG_CRITICAL = 4 BATTERY_FLAG_CHARGING = 8 BATTERY_FLAG_NO_BATTERY = 128 BATTERY_FLAG_UNKNOWN = 255 BATTERY_PERCENTAGE_UNKNOWN = 255 BATTERY_LIFE_UNKNOWN = -1 # Generated by h2py from d:\msdev\include\richedit.h cchTextLimitDefault = 32767 WM_CONTEXTMENU = 123 WM_PRINTCLIENT = 792 EN_MSGFILTER = 1792 EN_REQUESTRESIZE = 1793 EN_SELCHANGE = 1794 EN_DROPFILES = 1795 EN_PROTECTED = 1796 EN_CORRECTTEXT = 1797 EN_STOPNOUNDO = 1798 EN_IMECHANGE = 1799 EN_SAVECLIPBOARD = 1800 EN_OLEOPFAILED = 1801 ENM_NONE = 0 ENM_CHANGE = 1 ENM_UPDATE = 2 ENM_SCROLL = 4 ENM_KEYEVENTS = 65536 ENM_MOUSEEVENTS = 131072 ENM_REQUESTRESIZE = 262144 ENM_SELCHANGE = 524288 ENM_DROPFILES = 1048576 ENM_PROTECTED = 2097152 ENM_CORRECTTEXT = 4194304 ENM_IMECHANGE = 8388608 ES_SAVESEL = 32768 ES_SUNKEN = 16384 ES_DISABLENOSCROLL = 8192 ES_SELECTIONBAR = 16777216 ES_EX_NOCALLOLEINIT = 16777216 ES_VERTICAL = 4194304 ES_NOIME = 524288 ES_SELFIME = 262144 ECO_AUTOWORDSELECTION = 1 ECO_AUTOVSCROLL = 64 ECO_AUTOHSCROLL = 128 ECO_NOHIDESEL = 256 ECO_READONLY = 2048 ECO_WANTRETURN = 4096 ECO_SAVESEL = 32768 ECO_SELECTIONBAR = 16777216 ECO_VERTICAL = 4194304 ECOOP_SET = 1 ECOOP_OR = 2 ECOOP_AND = 3 ECOOP_XOR = 4 WB_CLASSIFY = 3 WB_MOVEWORDLEFT = 4 WB_MOVEWORDRIGHT = 5 WB_LEFTBREAK = 6 WB_RIGHTBREAK = 7 WB_MOVEWORDPREV = 4 WB_MOVEWORDNEXT = 5 WB_PREVBREAK = 6 WB_NEXTBREAK = 7 PC_FOLLOWING = 1 PC_LEADING = 2 PC_OVERFLOW = 3 PC_DELIMITER = 4 WBF_WORDWRAP = 16 WBF_WORDBREAK = 32 WBF_OVERFLOW = 64 WBF_LEVEL1 = 128 WBF_LEVEL2 = 256 WBF_CUSTOM = 512 CFM_BOLD = 1 CFM_ITALIC = 2 CFM_UNDERLINE = 4 CFM_STRIKEOUT = 8 CFM_PROTECTED = 16 CFM_SIZE = -2147483648 CFM_COLOR = 1073741824 CFM_FACE = 536870912 CFM_OFFSET = 268435456 CFM_CHARSET = 134217728 CFE_BOLD = 1 CFE_ITALIC = 2 CFE_UNDERLINE = 4 CFE_STRIKEOUT = 8 CFE_PROTECTED = 16 CFE_AUTOCOLOR = 1073741824 yHeightCharPtsMost = 1638 SCF_SELECTION = 1 SCF_WORD = 2 SF_TEXT = 1 SF_RTF = 2 SF_RTFNOOBJS = 3 SF_TEXTIZED = 4 SFF_SELECTION = 32768 SFF_PLAINRTF = 16384 MAX_TAB_STOPS = 32 lDefaultTab = 720 PFM_STARTINDENT = 1 PFM_RIGHTINDENT = 2 PFM_OFFSET = 4 PFM_ALIGNMENT = 8 PFM_TABSTOPS = 16 PFM_NUMBERING = 32 PFM_OFFSETINDENT = -2147483648 PFN_BULLET = 1 PFA_LEFT = 1 PFA_RIGHT = 2 PFA_CENTER = 3 WM_NOTIFY = 78 SEL_EMPTY = 0 SEL_TEXT = 1 SEL_OBJECT = 2 SEL_MULTICHAR = 4 SEL_MULTIOBJECT = 8 OLEOP_DOVERB = 1 CF_RTF = "Rich Text Format" CF_RTFNOOBJS = "Rich Text Format Without Objects" CF_RETEXTOBJ = "RichEdit Text and Objects" # From wincon.h RIGHT_ALT_PRESSED = 1 # the right alt key is pressed. LEFT_ALT_PRESSED = 2 # the left alt key is pressed. RIGHT_CTRL_PRESSED = 4 # the right ctrl key is pressed. LEFT_CTRL_PRESSED = 8 # the left ctrl key is pressed. SHIFT_PRESSED = 16 # the shift key is pressed. NUMLOCK_ON = 32 # the numlock light is on. SCROLLLOCK_ON = 64 # the scrolllock light is on. CAPSLOCK_ON = 128 # the capslock light is on. ENHANCED_KEY = 256 # the key is enhanced. NLS_DBCSCHAR = 65536 # DBCS for JPN: SBCS/DBCS mode. NLS_ALPHANUMERIC = 0 # DBCS for JPN: Alphanumeric mode. NLS_KATAKANA = 131072 # DBCS for JPN: Katakana mode. NLS_HIRAGANA = 262144 # DBCS for JPN: Hiragana mode. NLS_ROMAN = 4194304 # DBCS for JPN: Roman/Noroman mode. NLS_IME_CONVERSION = 8388608 # DBCS for JPN: IME conversion. NLS_IME_DISABLE = 536870912 # DBCS for JPN: IME enable/disable. FROM_LEFT_1ST_BUTTON_PRESSED = 1 RIGHTMOST_BUTTON_PRESSED = 2 FROM_LEFT_2ND_BUTTON_PRESSED = 4 FROM_LEFT_3RD_BUTTON_PRESSED = 8 FROM_LEFT_4TH_BUTTON_PRESSED = 16 CTRL_C_EVENT = 0 CTRL_BREAK_EVENT = 1 CTRL_CLOSE_EVENT = 2 CTRL_LOGOFF_EVENT = 5 CTRL_SHUTDOWN_EVENT = 6 MOUSE_MOVED = 1 DOUBLE_CLICK = 2 MOUSE_WHEELED = 4 #property sheet window messages from prsht.h PSM_SETCURSEL = (WM_USER + 101) PSM_REMOVEPAGE = (WM_USER + 102) PSM_ADDPAGE = (WM_USER + 103) PSM_CHANGED = (WM_USER + 104) PSM_RESTARTWINDOWS = (WM_USER + 105) PSM_REBOOTSYSTEM = (WM_USER + 106) PSM_CANCELTOCLOSE = (WM_USER + 107) PSM_QUERYSIBLINGS = (WM_USER + 108) PSM_UNCHANGED = (WM_USER + 109) PSM_APPLY = (WM_USER + 110) PSM_SETTITLEA = (WM_USER + 111) PSM_SETTITLEW = (WM_USER + 120) PSM_SETWIZBUTTONS = (WM_USER + 112) PSM_PRESSBUTTON = (WM_USER + 113) PSM_SETCURSELID = (WM_USER + 114) PSM_SETFINISHTEXTA = (WM_USER + 115) PSM_SETFINISHTEXTW = (WM_USER + 121) PSM_GETTABCONTROL = (WM_USER + 116) PSM_ISDIALOGMESSAGE = (WM_USER + 117) PSM_GETCURRENTPAGEHWND = (WM_USER + 118) PSM_INSERTPAGE = (WM_USER + 119) PSM_SETHEADERTITLEA = (WM_USER + 125) PSM_SETHEADERTITLEW = (WM_USER + 126) PSM_SETHEADERSUBTITLEA = (WM_USER + 127) PSM_SETHEADERSUBTITLEW = (WM_USER + 128) PSM_HWNDTOINDEX = (WM_USER + 129) PSM_INDEXTOHWND = (WM_USER + 130) PSM_PAGETOINDEX = (WM_USER + 131) PSM_INDEXTOPAGE = (WM_USER + 132) PSM_IDTOINDEX = (WM_USER + 133) PSM_INDEXTOID = (WM_USER + 134) PSM_GETRESULT = (WM_USER + 135) PSM_RECALCPAGESIZES = (WM_USER + 136) # GetUserNameEx/GetComputerNameEx NameUnknown = 0 NameFullyQualifiedDN = 1 NameSamCompatible = 2 NameDisplay = 3 NameUniqueId = 6 NameCanonical = 7 NameUserPrincipal = 8 NameCanonicalEx = 9 NameServicePrincipal = 10 NameDnsDomain = 12 ComputerNameNetBIOS = 0 ComputerNameDnsHostname = 1 ComputerNameDnsDomain = 2 ComputerNameDnsFullyQualified = 3 ComputerNamePhysicalNetBIOS = 4 ComputerNamePhysicalDnsHostname = 5 ComputerNamePhysicalDnsDomain = 6 ComputerNamePhysicalDnsFullyQualified = 7 LWA_COLORKEY = 0x00000001 LWA_ALPHA = 0x00000002 ULW_COLORKEY = 0x00000001 ULW_ALPHA = 0x00000002 ULW_OPAQUE = 0x00000004 # WinDef.h TRUE = 1 FALSE = 0 MAX_PATH = 260 # WinGDI.h AC_SRC_OVER = 0 AC_SRC_ALPHA = 1 GRADIENT_FILL_RECT_H = 0 GRADIENT_FILL_RECT_V = 1 GRADIENT_FILL_TRIANGLE = 2 GRADIENT_FILL_OP_FLAG = 255 # Bizarrely missing from any platform header. Ref: # http://www.codeguru.com/forum/archive/index.php/t-426785.html MAPVK_VK_TO_VSC = 0 MAPVK_VSC_TO_VK = 1 MAPVK_VK_TO_CHAR = 2 MAPVK_VSC_TO_VK_EX = 3 USER_TIMER_MAXIMUM = 0x7fffffff # From WinBase.h INFINITE = 0xffffffff
Python
#!/usr/bin/python # $Id: $ import struct from ctypes import * import pyglet import constants from types import * IS64 = struct.calcsize("P") == 8 _debug_win32 = pyglet.options['debug_win32'] if _debug_win32: import traceback _GetLastError = windll.kernel32.GetLastError _SetLastError = windll.kernel32.SetLastError _FormatMessageA = windll.kernel32.FormatMessageA _log_win32 = open('debug_win32.log', 'w') def format_error(err): msg = create_string_buffer(256) _FormatMessageA(constants.FORMAT_MESSAGE_FROM_SYSTEM, c_void_p(), err, 0, msg, len(msg), c_void_p()) return msg.value class DebugLibrary(object): def __init__(self, lib): self.lib = lib def __getattr__(self, name): fn = getattr(self.lib, name) def f(*args): _SetLastError(0) result = fn(*args) err = _GetLastError() if err != 0: for entry in traceback.format_list(traceback.extract_stack()[:-1]): _log_win32.write(entry) print >> _log_win32, format_error(err) return result return f else: DebugLibrary = lambda lib: lib _gdi32 = DebugLibrary(windll.gdi32) _kernel32 = DebugLibrary(windll.kernel32) _user32 = DebugLibrary(windll.user32) # _gdi32 _gdi32.AddFontMemResourceEx.restype = HANDLE _gdi32.AddFontMemResourceEx.argtypes = [PVOID, DWORD, PVOID, POINTER(DWORD)] _gdi32.ChoosePixelFormat.restype = c_int _gdi32.ChoosePixelFormat.argtypes = [HDC, POINTER(PIXELFORMATDESCRIPTOR)] _gdi32.CreateBitmap.restype = HBITMAP _gdi32.CreateBitmap.argtypes = [c_int, c_int, UINT, UINT, c_void_p] _gdi32.CreateCompatibleDC.restype = HDC _gdi32.CreateCompatibleDC.argtypes = [HDC] _gdi32.CreateDIBitmap.restype = HBITMAP _gdi32.CreateDIBitmap.argtypes = [HDC, POINTER(BITMAPINFOHEADER), DWORD, c_void_p, POINTER(BITMAPINFO), UINT] _gdi32.CreateDIBSection.restype = HBITMAP _gdi32.CreateDIBSection.argtypes = [HDC, c_void_p, UINT, c_void_p, HANDLE, DWORD] # POINTER(BITMAPINFO) _gdi32.CreateFontIndirectA.restype = HFONT _gdi32.CreateFontIndirectA.argtypes = [POINTER(LOGFONT)] _gdi32.DeleteDC.restype = BOOL _gdi32.DeleteDC.argtypes = [HDC] _gdi32.DeleteObject.restype = BOOL _gdi32.DeleteObject.argtypes = [HGDIOBJ] _gdi32.DescribePixelFormat.restype = c_int _gdi32.DescribePixelFormat.argtypes = [HDC, c_int, UINT, POINTER(PIXELFORMATDESCRIPTOR)] _gdi32.ExtTextOutA.restype = BOOL _gdi32.ExtTextOutA.argtypes = [HDC, c_int, c_int, UINT, LPRECT, c_char_p, UINT, POINTER(INT)] _gdi32.GdiFlush.restype = BOOL _gdi32.GdiFlush.argtypes = [] _gdi32.GetCharABCWidthsW.restype = BOOL _gdi32.GetCharABCWidthsW.argtypes = [HDC, UINT, UINT, POINTER(ABC)] _gdi32.GetCharWidth32W.restype = BOOL _gdi32.GetCharWidth32W.argtypes = [HDC, UINT, UINT, POINTER(INT)] _gdi32.GetStockObject.restype = HGDIOBJ _gdi32.GetStockObject.argtypes = [c_int] _gdi32.GetTextMetricsA.restype = BOOL _gdi32.GetTextMetricsA.argtypes = [HDC, POINTER(TEXTMETRIC)] _gdi32.SelectObject.restype = HGDIOBJ _gdi32.SelectObject.argtypes = [HDC, HGDIOBJ] _gdi32.SetBkColor.restype = COLORREF _gdi32.SetBkColor.argtypes = [HDC, COLORREF] _gdi32.SetBkMode.restype = c_int _gdi32.SetBkMode.argtypes = [HDC, c_int] _gdi32.SetPixelFormat.restype = BOOL _gdi32.SetPixelFormat.argtypes = [HDC, c_int, POINTER(PIXELFORMATDESCRIPTOR)] _gdi32.SetTextColor.restype = COLORREF _gdi32.SetTextColor.argtypes = [HDC, COLORREF] _kernel32.CloseHandle.restype = BOOL _kernel32.CloseHandle.argtypes = [HANDLE] _kernel32.CreateEventW.restype = HANDLE _kernel32.CreateEventW.argtypes = [POINTER(SECURITY_ATTRIBUTES), BOOL, BOOL, c_wchar_p] _kernel32.CreateWaitableTimerA.restype = HANDLE _kernel32.CreateWaitableTimerA.argtypes = [POINTER(SECURITY_ATTRIBUTES), BOOL, c_char_p] _kernel32.GetCurrentThreadId.restype = DWORD _kernel32.GetCurrentThreadId.argtypes = [] _kernel32.GetModuleHandleW.restype = HMODULE _kernel32.GetModuleHandleW.argtypes = [c_wchar_p] _kernel32.GlobalAlloc.restype = HGLOBAL _kernel32.GlobalAlloc.argtypes = [UINT, c_size_t] _kernel32.GlobalLock.restype = LPVOID _kernel32.GlobalLock.argtypes = [HGLOBAL] _kernel32.GlobalUnlock.restype = BOOL _kernel32.GlobalUnlock.argtypes = [HGLOBAL] _kernel32.SetLastError.restype = DWORD _kernel32.SetLastError.argtypes = [] _kernel32.SetWaitableTimer.restype = BOOL _kernel32.SetWaitableTimer.argtypes = [HANDLE, POINTER(LARGE_INTEGER), LONG, LPVOID, LPVOID, BOOL] # TIMERAPCPROC _kernel32.WaitForSingleObject.restype = DWORD _kernel32.WaitForSingleObject.argtypes = [HANDLE, DWORD] _user32.AdjustWindowRectEx.restype = BOOL _user32.AdjustWindowRectEx.argtypes = [LPRECT, DWORD, BOOL, DWORD] _user32.ChangeDisplaySettingsExW.restype = LONG _user32.ChangeDisplaySettingsExW.argtypes = [c_wchar_p, POINTER(DEVMODE), HWND, DWORD, LPVOID] _user32.ClientToScreen.restype = BOOL _user32.ClientToScreen.argtypes = [HWND, LPPOINT] _user32.ClipCursor.restype = BOOL _user32.ClipCursor.argtypes = [LPRECT] _user32.CreateIconIndirect.restype = HICON _user32.CreateIconIndirect.argtypes = [POINTER(ICONINFO)] _user32.CreateWindowExW.restype = HWND _user32.CreateWindowExW.argtypes = [DWORD, c_wchar_p, c_wchar_p, DWORD, c_int, c_int, c_int, c_int, HWND, HMENU, HINSTANCE, LPVOID] _user32.DefWindowProcW.restype = LRESULT _user32.DefWindowProcW.argtypes = [HWND, UINT, WPARAM, LPARAM] _user32.DestroyWindow.restype = BOOL _user32.DestroyWindow.argtypes = [HWND] _user32.DispatchMessageW.restype = LRESULT _user32.DispatchMessageW.argtypes = [LPMSG] _user32.EnumDisplayMonitors.restype = BOOL _user32.EnumDisplayMonitors.argtypes = [HDC, LPRECT, MONITORENUMPROC, LPARAM] _user32.EnumDisplaySettingsW.restype = BOOL _user32.EnumDisplaySettingsW.argtypes = [c_wchar_p, DWORD, POINTER(DEVMODE)] _user32.FillRect.restype = c_int _user32.FillRect.argtypes = [HDC, LPRECT, HBRUSH] _user32.GetClientRect.restype = BOOL _user32.GetClientRect.argtypes = [HWND, LPRECT] _user32.GetCursorPos.restype = BOOL _user32.GetCursorPos.argtypes = [LPPOINT] # workaround for win 64-bit, see issue #664 _user32.GetDC.restype = c_void_p # HDC _user32.GetDC.argtypes = [c_void_p] # [HWND] _user32.GetDesktopWindow.restype = HWND _user32.GetDesktopWindow.argtypes = [] _user32.GetKeyState.restype = c_short _user32.GetKeyState.argtypes = [c_int] _user32.GetMessageW.restype = BOOL _user32.GetMessageW.argtypes = [LPMSG, HWND, UINT, UINT] _user32.GetMonitorInfoW.restype = BOOL _user32.GetMonitorInfoW.argtypes = [HMONITOR, POINTER(MONITORINFOEX)] _user32.GetQueueStatus.restype = DWORD _user32.GetQueueStatus.argtypes = [UINT] _user32.GetSystemMetrics.restype = c_int _user32.GetSystemMetrics.argtypes = [c_int] _user32.LoadCursorW.restype = HCURSOR _user32.LoadCursorW.argtypes = [HINSTANCE, c_wchar_p] _user32.LoadIconW.restype = HICON _user32.LoadIconW.argtypes = [HINSTANCE, c_wchar_p] _user32.MapVirtualKeyW.restype = UINT _user32.MapVirtualKeyW.argtypes = [UINT, UINT] _user32.MapWindowPoints.restype = c_int _user32.MapWindowPoints.argtypes = [HWND, HWND, c_void_p, UINT] # HWND, HWND, LPPOINT, UINT _user32.MsgWaitForMultipleObjects.restype = DWORD _user32.MsgWaitForMultipleObjects.argtypes = [DWORD, POINTER(HANDLE), BOOL, DWORD, DWORD] _user32.PeekMessageW.restype = BOOL _user32.PeekMessageW.argtypes = [LPMSG, HWND, UINT, UINT, UINT] _user32.PostThreadMessageW.restype = BOOL _user32.PostThreadMessageW.argtypes = [DWORD, UINT, WPARAM, LPARAM] _user32.RegisterClassW.restype = ATOM _user32.RegisterClassW.argtypes = [POINTER(WNDCLASS)] _user32.RegisterHotKey.restype = BOOL _user32.RegisterHotKey.argtypes = [HWND, c_int, UINT, UINT] _user32.ReleaseCapture.restype = BOOL _user32.ReleaseCapture.argtypes = [] # workaround for win 64-bit, see issue #664 _user32.ReleaseDC.restype = c_int32 # c_int _user32.ReleaseDC.argtypes = [c_void_p, c_void_p] # [HWND, HDC] _user32.ScreenToClient.restype = BOOL _user32.ScreenToClient.argtypes = [HWND, LPPOINT] _user32.SetCapture.restype = HWND _user32.SetCapture.argtypes = [HWND] _user32.SetClassLongW.restype = DWORD _user32.SetClassLongW.argtypes = [HWND, c_int, LONG] if IS64: _user32.SetClassLongPtrW.restype = ULONG _user32.SetClassLongPtrW.argtypes = [HWND, c_int, LONG_PTR] else: _user32.SetClassLongPtrW = _user32.SetClassLongW _user32.SetCursor.restype = HCURSOR _user32.SetCursor.argtypes = [HCURSOR] _user32.SetCursorPos.restype = BOOL _user32.SetCursorPos.argtypes = [c_int, c_int] _user32.SetFocus.restype = HWND _user32.SetFocus.argtypes = [HWND] _user32.SetForegroundWindow.restype = BOOL _user32.SetForegroundWindow.argtypes = [HWND] _user32.SetTimer.restype = UINT_PTR _user32.SetTimer.argtypes = [HWND, UINT_PTR, UINT, TIMERPROC] _user32.SetWindowLongW.restype = LONG _user32.SetWindowLongW.argtypes = [HWND, c_int, LONG] _user32.SetWindowPos.restype = BOOL _user32.SetWindowPos.argtypes = [HWND, HWND, c_int, c_int, c_int, c_int, UINT] _user32.SetWindowTextW.restype = BOOL _user32.SetWindowTextW.argtypes = [HWND, c_wchar_p] _user32.ShowCursor.restype = c_int _user32.ShowCursor.argtypes = [BOOL] _user32.ShowWindow.restype = BOOL _user32.ShowWindow.argtypes = [HWND, c_int] _user32.TrackMouseEvent.restype = BOOL _user32.TrackMouseEvent.argtypes = [POINTER(TRACKMOUSEEVENT)] _user32.TranslateMessage.restype = BOOL _user32.TranslateMessage.argtypes = [LPMSG] _user32.UnregisterClassW.restype = BOOL _user32.UnregisterClassW.argtypes = [c_wchar_p, HINSTANCE] _user32.UnregisterHotKey.restype = BOOL _user32.UnregisterHotKey.argtypes = [HWND, c_int]
Python
import ctypes from pyglet import com lib = ctypes.oledll.dinput8 LPVOID = ctypes.c_void_p WORD = ctypes.c_uint16 DWORD = ctypes.c_uint32 LPDWORD = ctypes.POINTER(DWORD) BOOL = ctypes.c_int WCHAR = ctypes.c_wchar UINT = ctypes.c_uint HWND = ctypes.c_uint32 HANDLE = LPVOID MAX_PATH = 260 DIENUM_STOP = 0 DIENUM_CONTINUE = 1 DIEDFL_ALLDEVICES = 0x00000000 DIEDFL_ATTACHEDONLY = 0x00000001 DIEDFL_FORCEFEEDBACK = 0x00000100 DIEDFL_INCLUDEALIASES = 0x00010000 DIEDFL_INCLUDEPHANTOMS = 0x00020000 DIEDFL_INCLUDEHIDDEN = 0x00040000 DI8DEVCLASS_ALL = 0 DI8DEVCLASS_DEVICE = 1 DI8DEVCLASS_POINTER = 2 DI8DEVCLASS_KEYBOARD = 3 DI8DEVCLASS_GAMECTRL = 4 DI8DEVTYPE_DEVICE = 0x11 DI8DEVTYPE_MOUSE = 0x12 DI8DEVTYPE_KEYBOARD = 0x13 DI8DEVTYPE_JOYSTICK = 0x14 DI8DEVTYPE_GAMEPAD = 0x15 DI8DEVTYPE_DRIVING = 0x16 DI8DEVTYPE_FLIGHT = 0x17 DI8DEVTYPE_1STPERSON = 0x18 DI8DEVTYPE_DEVICECTRL = 0x19 DI8DEVTYPE_SCREENPOINTER = 0x1A DI8DEVTYPE_REMOTE = 0x1B DI8DEVTYPE_SUPPLEMENTAL = 0x1C DI8DEVTYPEMOUSE_UNKNOWN = 1 DI8DEVTYPEMOUSE_TRADITIONAL = 2 DI8DEVTYPEMOUSE_FINGERSTICK = 3 DI8DEVTYPEMOUSE_TOUCHPAD = 4 DI8DEVTYPEMOUSE_TRACKBALL = 5 DI8DEVTYPEMOUSE_ABSOLUTE = 6 DI8DEVTYPEKEYBOARD_UNKNOWN = 0 DI8DEVTYPEKEYBOARD_PCXT = 1 DI8DEVTYPEKEYBOARD_OLIVETTI = 2 DI8DEVTYPEKEYBOARD_PCAT = 3 DI8DEVTYPEKEYBOARD_PCENH = 4 DI8DEVTYPEKEYBOARD_NOKIA1050 = 5 DI8DEVTYPEKEYBOARD_NOKIA9140 = 6 DI8DEVTYPEKEYBOARD_NEC98 = 7 DI8DEVTYPEKEYBOARD_NEC98LAPTOP = 8 DI8DEVTYPEKEYBOARD_NEC98106 = 9 DI8DEVTYPEKEYBOARD_JAPAN106 = 10 DI8DEVTYPEKEYBOARD_JAPANAX = 11 DI8DEVTYPEKEYBOARD_J3100 = 12 DI8DEVTYPE_LIMITEDGAMESUBTYPE = 1 DI8DEVTYPEJOYSTICK_LIMITED = DI8DEVTYPE_LIMITEDGAMESUBTYPE DI8DEVTYPEJOYSTICK_STANDARD = 2 DI8DEVTYPEGAMEPAD_LIMITED = DI8DEVTYPE_LIMITEDGAMESUBTYPE DI8DEVTYPEGAMEPAD_STANDARD = 2 DI8DEVTYPEGAMEPAD_TILT = 3 DI8DEVTYPEDRIVING_LIMITED = DI8DEVTYPE_LIMITEDGAMESUBTYPE DI8DEVTYPEDRIVING_COMBINEDPEDALS = 2 DI8DEVTYPEDRIVING_DUALPEDALS = 3 DI8DEVTYPEDRIVING_THREEPEDALS = 4 DI8DEVTYPEDRIVING_HANDHELD = 5 DI8DEVTYPEFLIGHT_LIMITED = DI8DEVTYPE_LIMITEDGAMESUBTYPE DI8DEVTYPEFLIGHT_STICK = 2 DI8DEVTYPEFLIGHT_YOKE = 3 DI8DEVTYPEFLIGHT_RC = 4 DI8DEVTYPE1STPERSON_LIMITED = DI8DEVTYPE_LIMITEDGAMESUBTYPE DI8DEVTYPE1STPERSON_UNKNOWN = 2 DI8DEVTYPE1STPERSON_SIXDOF = 3 DI8DEVTYPE1STPERSON_SHOOTER = 4 DI8DEVTYPESCREENPTR_UNKNOWN = 2 DI8DEVTYPESCREENPTR_LIGHTGUN = 3 DI8DEVTYPESCREENPTR_LIGHTPEN = 4 DI8DEVTYPESCREENPTR_TOUCH = 5 DI8DEVTYPEREMOTE_UNKNOWN = 2 DI8DEVTYPEDEVICECTRL_UNKNOWN = 2 DI8DEVTYPEDEVICECTRL_COMMSSELECTION = 3 DI8DEVTYPEDEVICECTRL_COMMSSELECTION_HARDWIRED = 4 DI8DEVTYPESUPPLEMENTAL_UNKNOWN = 2 DI8DEVTYPESUPPLEMENTAL_2NDHANDCONTROLLER = 3 DI8DEVTYPESUPPLEMENTAL_HEADTRACKER = 4 DI8DEVTYPESUPPLEMENTAL_HANDTRACKER = 5 DI8DEVTYPESUPPLEMENTAL_SHIFTSTICKGATE = 6 DI8DEVTYPESUPPLEMENTAL_SHIFTER = 7 DI8DEVTYPESUPPLEMENTAL_THROTTLE = 8 DI8DEVTYPESUPPLEMENTAL_SPLITTHROTTLE = 9 DI8DEVTYPESUPPLEMENTAL_COMBINEDPEDALS = 10 DI8DEVTYPESUPPLEMENTAL_DUALPEDALS = 11 DI8DEVTYPESUPPLEMENTAL_THREEPEDALS = 12 DI8DEVTYPESUPPLEMENTAL_RUDDERPEDALS = 13 DIDC_ATTACHED = 0x00000001 DIDC_POLLEDDEVICE = 0x00000002 DIDC_EMULATED = 0x00000004 DIDC_POLLEDDATAFORMAT = 0x00000008 DIDC_FORCEFEEDBACK = 0x00000100 DIDC_FFATTACK = 0x00000200 DIDC_FFFADE = 0x00000400 DIDC_SATURATION = 0x00000800 DIDC_POSNEGCOEFFICIENTS = 0x00001000 DIDC_POSNEGSATURATION = 0x00002000 DIDC_DEADBAND = 0x00004000 DIDC_STARTDELAY = 0x00008000 DIDC_ALIAS = 0x00010000 DIDC_PHANTOM = 0x00020000 DIDC_HIDDEN = 0x00040000 def DIDFT_GETINSTANCE(n): return (n >> 8) & 0xffff DIDFT_ALL = 0x00000000 DIDFT_RELAXIS = 0x00000001 DIDFT_ABSAXIS = 0x00000002 DIDFT_AXIS = 0x00000003 DIDFT_PSHBUTTON = 0x00000004 DIDFT_TGLBUTTON = 0x00000008 DIDFT_BUTTON = 0x0000000C DIDFT_POV = 0x00000010 DIDFT_COLLECTION = 0x00000040 DIDFT_NODATA = 0x00000080 DIDFT_ANYINSTANCE = 0x00FFFF00 DIDFT_INSTANCEMASK = DIDFT_ANYINSTANCE DIDFT_FFACTUATOR = 0x01000000 DIDFT_FFEFFECTTRIGGER = 0x02000000 DIDFT_OUTPUT = 0x10000000 DIDFT_VENDORDEFINED = 0x04000000 DIDFT_ALIAS = 0x08000000 DIDFT_OPTIONAL = 0x80000000 DIDFT_NOCOLLECTION = 0x00FFFF00 DIA_FORCEFEEDBACK = 0x00000001 DIA_APPMAPPED = 0x00000002 DIA_APPNOMAP = 0x00000004 DIA_NORANGE = 0x00000008 DIA_APPFIXED = 0x00000010 DIAH_UNMAPPED = 0x00000000 DIAH_USERCONFIG = 0x00000001 DIAH_APPREQUESTED = 0x00000002 DIAH_HWAPP = 0x00000004 DIAH_HWDEFAULT = 0x00000008 DIAH_DEFAULT = 0x00000020 DIAH_ERROR = 0x80000000 DIAFTS_NEWDEVICELOW = 0xFFFFFFFF DIAFTS_NEWDEVICEHIGH = 0xFFFFFFFF DIAFTS_UNUSEDDEVICELOW = 0x00000000 DIAFTS_UNUSEDDEVICEHIGH = 0x00000000 DIDBAM_DEFAULT = 0x00000000 DIDBAM_PRESERVE = 0x00000001 DIDBAM_INITIALIZE = 0x00000002 DIDBAM_HWDEFAULTS = 0x00000004 DIDSAM_DEFAULT = 0x00000000 DIDSAM_NOUSER = 0x00000001 DIDSAM_FORCESAVE = 0x00000002 DICD_DEFAULT = 0x00000000 DICD_EDIT = 0x00000001 DIDOI_FFACTUATOR = 0x00000001 DIDOI_FFEFFECTTRIGGER = 0x00000002 DIDOI_POLLED = 0x00008000 DIDOI_ASPECTPOSITION = 0x00000100 DIDOI_ASPECTVELOCITY = 0x00000200 DIDOI_ASPECTACCEL = 0x00000300 DIDOI_ASPECTFORCE = 0x00000400 DIDOI_ASPECTMASK = 0x00000F00 DIDOI_GUIDISUSAGE = 0x00010000 DIPH_DEVICE = 0 DIPH_BYOFFSET = 1 DIPH_BYID = 2 DIPH_BYUSAGE = 3 DISCL_EXCLUSIVE = 0x00000001 DISCL_NONEXCLUSIVE = 0x00000002 DISCL_FOREGROUND = 0x00000004 DISCL_BACKGROUND = 0x00000008 DISCL_NOWINKEY = 0x00000010 DIPROP_BUFFERSIZE = 1 GUID_XAxis = \ com.GUID(0xA36D02E0,0xC9F3,0x11CF,0xBF,0xC7,0x44,0x45,0x53,0x54,0x00,0x00) class DIDEVICEINSTANCE(ctypes.Structure): _fields_ = ( ('dwSize', DWORD), ('guidInstance', com.GUID), ('guidProduct', com.GUID), ('dwDevType', DWORD), ('tszInstanceName', WCHAR * MAX_PATH), ('tszProductName', WCHAR * MAX_PATH), ('guidFFDriver', com.GUID), ('wUsagePage', WORD), ('wUsage', WORD) ) LPDIDEVICEINSTANCE = ctypes.POINTER(DIDEVICEINSTANCE) LPDIENUMDEVICESCALLBACK = ctypes.WINFUNCTYPE(BOOL, LPDIDEVICEINSTANCE, LPVOID) class DIDEVICEOBJECTINSTANCE(ctypes.Structure): _fields_ = ( ('dwSize', DWORD), ('guidType', com.GUID), ('dwOfs', DWORD), ('dwType', DWORD), ('dwFlags', DWORD), ('tszName', WCHAR * MAX_PATH), ('dwFFMaxForce', DWORD), ('dwFFForceResolution', DWORD), ('wCollectionNumber', WORD), ('wDesignatorIndex', WORD), ('wUsagePage', WORD), ('wUsage', WORD), ('dwDimension', DWORD), ('wExponent', WORD), ('wReportId', WORD) ) LPDIDEVICEOBJECTINSTANCE = ctypes.POINTER(DIDEVICEOBJECTINSTANCE) LPDIENUMDEVICEOBJECTSCALLBACK = \ ctypes.WINFUNCTYPE( BOOL, LPDIDEVICEOBJECTINSTANCE, LPVOID) class DIOBJECTDATAFORMAT(ctypes.Structure): _fields_ = ( ('pguid', ctypes.POINTER(com.GUID)), ('dwOfs', DWORD), ('dwType', DWORD), ('dwFlags', DWORD) ) __slots__ = [n for n, t in _fields_] LPDIOBJECTDATAFORMAT = ctypes.POINTER(DIOBJECTDATAFORMAT) class DIDATAFORMAT(ctypes.Structure): _fields_ = ( ('dwSize', DWORD), ('dwObjSize', DWORD), ('dwFlags', DWORD), ('dwDataSize', DWORD), ('dwNumObjs', DWORD), ('rgodf', LPDIOBJECTDATAFORMAT) ) __slots__ = [n for n, t in _fields_] LPDIDATAFORMAT = ctypes.POINTER(DIDATAFORMAT) class DIDEVICEOBJECTDATA(ctypes.Structure): _fields_ = ( ('dwOfs', DWORD), ('dwData', DWORD), ('dwTimeStamp', DWORD), ('dwSequence', DWORD), ('uAppData', ctypes.POINTER(UINT)) ) LPDIDEVICEOBJECTDATA = ctypes.POINTER(DIDEVICEOBJECTDATA) class DIPROPHEADER(ctypes.Structure): _fields_ = ( ('dwSize', DWORD), ('dwHeaderSize', DWORD), ('dwObj', DWORD), ('dwHow', DWORD) ) LPDIPROPHEADER = ctypes.POINTER(DIPROPHEADER) class DIPROPDWORD(ctypes.Structure): _fields_ = ( ('diph', DIPROPHEADER), ('dwData', DWORD) ) # All method names in the interfaces are filled in, but unused (so far) # methods have no parameters.. they'll crash when we try and use them, at # which point we can go in and fill them in. # IDirect* interfaces are all Unicode (e.g. IDirectInputDevice8W). class IDirectInputDevice8(com.IUnknown): _methods_ = [ ('GetCapabilities', com.STDMETHOD()), ('EnumObjects', com.STDMETHOD(LPDIENUMDEVICEOBJECTSCALLBACK, LPVOID, DWORD)), ('GetProperty', com.STDMETHOD()), ('SetProperty', com.STDMETHOD(LPVOID, LPDIPROPHEADER)), ('Acquire', com.STDMETHOD()), ('Unacquire', com.STDMETHOD()), ('GetDeviceState', com.STDMETHOD()), ('GetDeviceData', com.STDMETHOD(DWORD, LPDIDEVICEOBJECTDATA, LPDWORD, DWORD)), ('SetDataFormat', com.STDMETHOD(LPDIDATAFORMAT)), ('SetEventNotification', com.STDMETHOD(HANDLE)), ('SetCooperativeLevel', com.STDMETHOD(HWND, DWORD)), ('GetObjectInfo', com.STDMETHOD()), ('GetDeviceInfo', com.STDMETHOD()), ('RunControlPanel', com.STDMETHOD()), ('Initialize', com.STDMETHOD()), ('CreateEffect', com.STDMETHOD()), ('EnumEffects', com.STDMETHOD()), ('GetEffectInfo', com.STDMETHOD()), ('GetForceFeedbackState', com.STDMETHOD()), ('SendForceFeedbackCommand', com.STDMETHOD()), ('EnumCreatedEffectObjects', com.STDMETHOD()), ('Escape', com.STDMETHOD()), ('Poll', com.STDMETHOD()), ('SendDeviceData', com.STDMETHOD()), ('EnumEffectsInFile', com.STDMETHOD()), ('WriteEffectToFile', com.STDMETHOD()), ('BuildActionMap', com.STDMETHOD()), ('SetActionMap', com.STDMETHOD()), ('GetImageInfo', com.STDMETHOD()), ] class IDirectInput8(com.IUnknown): _methods_ = [ ('CreateDevice', com.STDMETHOD(ctypes.POINTER(com.GUID), ctypes.POINTER(IDirectInputDevice8), ctypes.c_void_p)), ('EnumDevices', com.STDMETHOD(DWORD, LPDIENUMDEVICESCALLBACK, LPVOID, DWORD)), ('GetDeviceStatus', com.STDMETHOD()), ('RunControlPanel', com.STDMETHOD()), ('Initialize', com.STDMETHOD()), ('FindDevice', com.STDMETHOD()), ('EnumDevicesBySemantics', com.STDMETHOD()), ('ConfigureDevices', com.STDMETHOD()), ] IID_IDirectInput8W = \ com.GUID(0xBF798031,0x483A,0x4DA2,0xAA,0x99,0x5D,0x64,0xED,0x36,0x97,0x00) DIRECTINPUT_VERSION = 0x0800 DirectInput8Create = lib.DirectInput8Create DirectInput8Create.argtypes = \ (ctypes.c_void_p, DWORD, com.LPGUID, ctypes.c_void_p, ctypes.c_void_p)
Python
#!/usr/bin/python # $Id:$ import ctypes lib = ctypes.windll.wintab32 LONG = ctypes.c_long BOOL = ctypes.c_int UINT = ctypes.c_uint WORD = ctypes.c_uint16 DWORD = ctypes.c_uint32 WCHAR = ctypes.c_wchar FIX32 = DWORD WTPKT = DWORD LCNAMELEN = 40 class AXIS(ctypes.Structure): _fields_ = ( ('axMin', LONG), ('axMax', LONG), ('axUnits', UINT), ('axResolution', FIX32) ) def get_scale(self): return 1 / float(self.axMax - self.axMin) def get_bias(self): return -self.axMin class ORIENTATION(ctypes.Structure): _fields_ = ( ('orAzimuth', ctypes.c_int), ('orAltitude', ctypes.c_int), ('orTwist', ctypes.c_int) ) class ROTATION(ctypes.Structure): _fields_ = ( ('roPitch', ctypes.c_int), ('roRoll', ctypes.c_int), ('roYaw', ctypes.c_int), ) class LOGCONTEXT(ctypes.Structure): _fields_ = ( ('lcName', WCHAR * LCNAMELEN), ('lcOptions', UINT), ('lcStatus', UINT), ('lcLocks', UINT), ('lcMsgBase', UINT), ('lcDevice', UINT), ('lcPktRate', UINT), ('lcPktData', WTPKT), ('lcPktMode', WTPKT), ('lcMoveMask', WTPKT), ('lcBtnDnMask', DWORD), ('lcBtnUpMask', DWORD), ('lcInOrgX', LONG), ('lcInOrgY', LONG), ('lcInOrgZ', LONG), ('lcInExtX', LONG), ('lcInExtY', LONG), ('lcInExtZ', LONG), ('lcOutOrgX', LONG), ('lcOutOrgY', LONG), ('lcOutOrgZ', LONG), ('lcOutExtX', LONG), ('lcOutExtY', LONG), ('lcOutExtZ', LONG), ('lcSensX', FIX32), ('lcSensY', FIX32), ('lcSensZ', FIX32), ('lcSysMode', BOOL), ('lcSysOrgX', ctypes.c_int), ('lcSysOrgY', ctypes.c_int), ('lcSysExtX', ctypes.c_int), ('lcSysExtY', ctypes.c_int), ('lcSysSensX', FIX32), ('lcSysSensY', FIX32), ) # Custom packet format with fields # PK_CHANGED # PK_CURSOR # PK_BUTTONS # PK_X # PK_Y # PK_Z # PK_NORMAL_PRESSURE # PK_TANGENT_PRESSURE # PK_ORIENTATION (check for tilt extension instead)? class PACKET(ctypes.Structure): _fields_ = ( ('pkChanged', WTPKT), ('pkCursor', UINT), ('pkButtons', DWORD), ('pkX', LONG), ('pkY', LONG), ('pkZ', LONG), ('pkNormalPressure', UINT), ('pkTangentPressure', UINT), ('pkOrientation', ORIENTATION), ) PK_CONTEXT = 0x0001 # reporting context PK_STATUS = 0x0002 # status bits PK_TIME = 0x0004 # time stamp PK_CHANGED = 0x0008 # change bit vector PK_SERIAL_NUMBER = 0x0010 # packet serial number PK_CURSOR = 0x0020 # reporting cursor PK_BUTTONS = 0x0040 # button information PK_X = 0x0080 # x axis PK_Y = 0x0100 # y axis PK_Z = 0x0200 # z axis PK_NORMAL_PRESSURE = 0x0400 # normal or tip pressure PK_TANGENT_PRESSURE = 0x0800 # tangential or barrel pressure PK_ORIENTATION = 0x1000 # orientation info: tilts PK_ROTATION = 0x2000 # rotation info; 1.1 TU_NONE = 0 TU_INCHES = 1 TU_CENTIMETERS = 2 TU_CIRCLE = 3 # messages WT_DEFBASE = 0x7ff0 WT_MAXOFFSET = 0xf WT_PACKET = 0 # remember to add base WT_CTXOPEN = 1 WT_CTXCLOSE = 2 WT_CTXUPDATE = 3 WT_CTXOVERLAP = 4 WT_PROXIMITY = 5 WT_INFOCHANGE = 6 WT_CSRCHANGE = 7 # system button assignment values SBN_NONE = 0x00 SBN_LCLICK = 0x01 SBN_LDBLCLICK = 0x02 SBN_LDRAG = 0x03 SBN_RCLICK = 0x04 SBN_RDBLCLICK = 0x05 SBN_RDRAG = 0x06 SBN_MCLICK = 0x07 SBN_MDBLCLICK = 0x08 SBN_MDRAG = 0x09 # for Pen Windows SBN_PTCLICK = 0x10 SBN_PTDBLCLICK = 0x20 SBN_PTDRAG = 0x30 SBN_PNCLICK = 0x40 SBN_PNDBLCLICK = 0x50 SBN_PNDRAG = 0x60 SBN_P1CLICK = 0x70 SBN_P1DBLCLICK = 0x80 SBN_P1DRAG = 0x90 SBN_P2CLICK = 0xA0 SBN_P2DBLCLICK = 0xB0 SBN_P2DRAG = 0xC0 SBN_P3CLICK = 0xD0 SBN_P3DBLCLICK = 0xE0 SBN_P3DRAG = 0xF0 HWC_INTEGRATED = 0x0001 HWC_TOUCH = 0x0002 HWC_HARDPROX = 0x0004 HWC_PHYSID_CURSORS = 0x0008 # 1.1 CRC_MULTIMODE = 0x0001 # 1.1 CRC_AGGREGATE = 0x0002 # 1.1 CRC_INVERT = 0x0004 # 1.1 WTI_INTERFACE = 1 IFC_WINTABID = 1 IFC_SPECVERSION = 2 IFC_IMPLVERSION = 3 IFC_NDEVICES = 4 IFC_NCURSORS = 5 IFC_NCONTEXTS = 6 IFC_CTXOPTIONS = 7 IFC_CTXSAVESIZE = 8 IFC_NEXTENSIONS = 9 IFC_NMANAGERS = 10 IFC_MAX = 10 WTI_STATUS = 2 STA_CONTEXTS = 1 STA_SYSCTXS = 2 STA_PKTRATE = 3 STA_PKTDATA = 4 STA_MANAGERS = 5 STA_SYSTEM = 6 STA_BUTTONUSE = 7 STA_SYSBTNUSE = 8 STA_MAX = 8 WTI_DEFCONTEXT = 3 WTI_DEFSYSCTX = 4 WTI_DDCTXS = 400 # 1.1 WTI_DSCTXS = 500 # 1.1 CTX_NAME = 1 CTX_OPTIONS = 2 CTX_STATUS = 3 CTX_LOCKS = 4 CTX_MSGBASE = 5 CTX_DEVICE = 6 CTX_PKTRATE = 7 CTX_PKTDATA = 8 CTX_PKTMODE = 9 CTX_MOVEMASK = 10 CTX_BTNDNMASK = 11 CTX_BTNUPMASK = 12 CTX_INORGX = 13 CTX_INORGY = 14 CTX_INORGZ = 15 CTX_INEXTX = 16 CTX_INEXTY = 17 CTX_INEXTZ = 18 CTX_OUTORGX = 19 CTX_OUTORGY = 20 CTX_OUTORGZ = 21 CTX_OUTEXTX = 22 CTX_OUTEXTY = 23 CTX_OUTEXTZ = 24 CTX_SENSX = 25 CTX_SENSY = 26 CTX_SENSZ = 27 CTX_SYSMODE = 28 CTX_SYSORGX = 29 CTX_SYSORGY = 30 CTX_SYSEXTX = 31 CTX_SYSEXTY = 32 CTX_SYSSENSX = 33 CTX_SYSSENSY = 34 CTX_MAX = 34 WTI_DEVICES = 100 DVC_NAME = 1 DVC_HARDWARE = 2 DVC_NCSRTYPES = 3 DVC_FIRSTCSR = 4 DVC_PKTRATE = 5 DVC_PKTDATA = 6 DVC_PKTMODE = 7 DVC_CSRDATA = 8 DVC_XMARGIN = 9 DVC_YMARGIN = 10 DVC_ZMARGIN = 11 DVC_X = 12 DVC_Y = 13 DVC_Z = 14 DVC_NPRESSURE = 15 DVC_TPRESSURE = 16 DVC_ORIENTATION = 17 DVC_ROTATION = 18 # 1.1 DVC_PNPID = 19 # 1.1 DVC_MAX = 19 WTI_CURSORS = 200 CSR_NAME = 1 CSR_ACTIVE = 2 CSR_PKTDATA = 3 CSR_BUTTONS = 4 CSR_BUTTONBITS = 5 CSR_BTNNAMES = 6 CSR_BUTTONMAP = 7 CSR_SYSBTNMAP = 8 CSR_NPBUTTON = 9 CSR_NPBTNMARKS = 10 CSR_NPRESPONSE = 11 CSR_TPBUTTON = 12 CSR_TPBTNMARKS = 13 CSR_TPRESPONSE = 14 CSR_PHYSID = 15 # 1.1 CSR_MODE = 16 # 1.1 CSR_MINPKTDATA = 17 # 1.1 CSR_MINBUTTONS = 18 # 1.1 CSR_CAPABILITIES = 19 # 1.1 CSR_TYPE = 20 # 1.2 CSR_MAX = 20 WTI_EXTENSIONS = 300 EXT_NAME = 1 EXT_TAG = 2 EXT_MASK = 3 EXT_SIZE = 4 EXT_AXES = 5 EXT_DEFAULT = 6 EXT_DEFCONTEXT = 7 EXT_DEFSYSCTX = 8 EXT_CURSORS = 9 EXT_MAX = 109 # Allow 100 cursors CXO_SYSTEM = 0x0001 CXO_PEN = 0x0002 CXO_MESSAGES = 0x0004 CXO_MARGIN = 0x8000 CXO_MGNINSIDE = 0x4000 CXO_CSRMESSAGES = 0x0008 # 1.1 # context status values CXS_DISABLED = 0x0001 CXS_OBSCURED = 0x0002 CXS_ONTOP = 0x0004 # context lock values CXL_INSIZE = 0x0001 CXL_INASPECT = 0x0002 CXL_SENSITIVITY = 0x0004 CXL_MARGIN = 0x0008 CXL_SYSOUT = 0x0010 # packet status values TPS_PROXIMITY = 0x0001 TPS_QUEUE_ERR = 0x0002 TPS_MARGIN = 0x0004 TPS_GRAB = 0x0008 TPS_INVERT = 0x0010 # 1.1 TBN_NONE = 0 TBN_UP = 1 TBN_DOWN = 2 PKEXT_ABSOLUTE = 1 PKEXT_RELATIVE = 2 # Extension tags. WTX_OBT = 0 # Out of bounds tracking WTX_FKEYS = 1 # Function keys WTX_TILT = 2 # Raw Cartesian tilt; 1.1 WTX_CSRMASK = 3 # select input by cursor type; 1.1 WTX_XBTNMASK = 4 # Extended button mask; 1.1 WTX_EXPKEYS = 5 # ExpressKeys; 1.3
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Precise framerate calculation, scheduling and framerate limiting. Measuring time ============== The `tick` and `get_fps` functions can be used in conjunction to fulfil most games' basic requirements:: from pyglet import clock while True: dt = clock.tick() # ... update and render ... print 'FPS is %f' % clock.get_fps() The ``dt`` value returned gives the number of seconds (as a float) since the last "tick". The `get_fps` function averages the framerate over a sliding window of approximately 1 second. (You can calculate the instantaneous framerate by taking the reciprocal of ``dt``). Always remember to `tick` the clock! Limiting frame-rate =================== The framerate can be limited:: clock.set_fps_limit(60) This causes `clock` to sleep during each `tick` in an attempt to keep the number of ticks (frames) per second below 60. The implementation uses platform-dependent high-resolution sleep functions to achieve better accuracy with busy-waiting than would be possible using just the `time` module. Scheduling ========== You can schedule a function to be called every time the clock is ticked:: def callback(dt): print '%f seconds since last callback' % dt clock.schedule(callback) The `schedule_interval` method causes a function to be called every "n" seconds:: clock.schedule_interval(callback, .5) # called twice a second The `schedule_once` method causes a function to be called once "n" seconds in the future:: clock.schedule_once(callback, 5) # called in 5 seconds All of the `schedule` methods will pass on any additional args or keyword args you specify to the callback function:: def animate(dt, velocity, sprite): sprite.position += dt * velocity clock.schedule(animate, velocity=5.0, sprite=alien) You can cancel a function scheduled with any of these methods using `unschedule`:: clock.unschedule(animate) Displaying FPS ============== The ClockDisplay class provides a simple FPS counter. You should create an instance of ClockDisplay once during the application's start up:: fps_display = clock.ClockDisplay() Call draw on the ClockDisplay object for each frame:: fps_display.draw() There are several options to change the font, color and text displayed within the __init__ method. Using multiple clocks ===================== The clock functions are all relayed to an instance of `Clock` which is initialised with the module. You can get this instance to use directly:: clk = clock.get_default() You can also replace the default clock with your own: myclk = clock.Clock() clock.set_default(myclk) Each clock maintains its own set of scheduled functions and FPS limiting/measurement. Each clock must be "ticked" separately. Multiple and derived clocks potentially allow you to separate "game-time" and "wall-time", or to synchronise your clock to an audio or video stream instead of the system clock. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import time import ctypes import pyglet.lib from pyglet import compat_platform if compat_platform in ('win32', 'cygwin'): # Win32 Sleep function is only 10-millisecond resolution, so instead # use a waitable timer object, which has up to 100-nanosecond resolution # (hardware and implementation dependent, of course). _kernel32 = ctypes.windll.kernel32 class _ClockBase(object): def __init__(self): self._timer = _kernel32.CreateWaitableTimerA(None, True, None) def sleep(self, microseconds): delay = ctypes.c_longlong(int(-microseconds * 10)) _kernel32.SetWaitableTimer(self._timer, ctypes.byref(delay), 0, ctypes.c_void_p(), ctypes.c_void_p(), False) _kernel32.WaitForSingleObject(self._timer, 0xffffffff) _default_time_function = time.clock else: _c = pyglet.lib.load_library('c') _c.usleep.argtypes = [ctypes.c_ulong] class _ClockBase(object): def sleep(self, microseconds): _c.usleep(int(microseconds)) _default_time_function = time.time class _ScheduledItem(object): __slots__ = ['func', 'args', 'kwargs'] def __init__(self, func, args, kwargs): self.func = func self.args = args self.kwargs = kwargs class _ScheduledIntervalItem(object): __slots__ = ['func', 'interval', 'last_ts', 'next_ts', 'args', 'kwargs'] def __init__(self, func, interval, last_ts, next_ts, args, kwargs): self.func = func self.interval = interval self.last_ts = last_ts self.next_ts = next_ts self.args = args self.kwargs = kwargs def _dummy_schedule_func(*args, **kwargs): '''Dummy function that does nothing, placed onto zombie scheduled items to ensure they have no side effect if already queued inside tick() method. ''' pass class Clock(_ClockBase): '''Class for calculating and limiting framerate, and for calling scheduled functions. ''' #: The minimum amount of time in seconds this clock will attempt to sleep #: for when framerate limiting. Higher values will increase the #: accuracy of the limiting but also increase CPU usage while #: busy-waiting. Lower values mean the process sleeps more often, but is #: prone to over-sleep and run at a potentially lower or uneven framerate #: than desired. MIN_SLEEP = 0.005 #: The amount of time in seconds this clock subtracts from sleep values #: to compensate for lazy operating systems. SLEEP_UNDERSHOOT = MIN_SLEEP - 0.001 # List of functions to call every tick. _schedule_items = None # List of schedule interval items kept in sort order. _schedule_interval_items = None # If True, a sleep(0) is inserted on every tick. _force_sleep = False def __init__(self, fps_limit=None, time_function=_default_time_function): '''Initialise a Clock, with optional framerate limit and custom time function. :Parameters: `fps_limit` : float If not None, the maximum allowable framerate. Defaults to None. Deprecated in pyglet 1.2. `time_function` : function Function to return the elapsed time of the application, in seconds. Defaults to time.time, but can be replaced to allow for easy time dilation effects or game pausing. ''' super(Clock, self).__init__() self.time = time_function self.next_ts = self.time() self.last_ts = None self.times = [] self.set_fps_limit(fps_limit) self.cumulative_time = 0 self._schedule_items = [] self._schedule_interval_items = [] def update_time(self): '''Get the elapsed time since the last call to `update_time`. This updates the clock's internal measure of time and returns the difference since the last update (or since the clock was created). :since: pyglet 1.2 :rtype: float :return: The number of seconds since the last `update_time`, or 0 if this was the first time it was called. ''' ts = self.time() if self.last_ts is None: delta_t = 0 else: delta_t = ts - self.last_ts self.times.insert(0, delta_t) if len(self.times) > self.window_size: self.cumulative_time -= self.times.pop() self.cumulative_time += delta_t self.last_ts = ts return delta_t def call_scheduled_functions(self, dt): '''Call scheduled functions that elapsed on the last `update_time`. :since: pyglet 1.2 :Parameters: dt : float The elapsed time since the last update to pass to each scheduled function. This is *not* used to calculate which functions have elapsed. :rtype: bool :return: True if any functions were called, otherwise False. ''' ts = self.last_ts result = False # Call functions scheduled for every frame # Dupe list just in case one of the items unchedules itself for item in list(self._schedule_items): result = True item.func(dt, *item.args, **item.kwargs) # Call all scheduled interval functions and reschedule for future. need_resort = False # Dupe list just in case one of the items unchedules itself for item in list(self._schedule_interval_items): if item.next_ts > ts: break result = True item.func(ts - item.last_ts, *item.args, **item.kwargs) if item.interval: # Try to keep timing regular, even if overslept this time; # but don't schedule in the past (which could lead to # infinitely-worsing error). item.next_ts = item.last_ts + item.interval item.last_ts = ts if item.next_ts <= ts: if ts - item.next_ts < 0.05: # Only missed by a little bit, keep the same schedule item.next_ts = ts + item.interval else: # Missed by heaps, do a soft reschedule to avoid # lumping everything together. item.next_ts = self._get_soft_next_ts(ts, item.interval) # Fake last_ts to avoid repeatedly over-scheduling in # future. Unfortunately means the next reported dt is # incorrect (looks like interval but actually isn't). item.last_ts = item.next_ts - item.interval need_resort = True else: item.next_ts = None # Remove finished one-shots. self._schedule_interval_items = \ [item for item in self._schedule_interval_items \ if item.next_ts is not None] if need_resort: # TODO bubble up changed items might be faster self._schedule_interval_items.sort(key=lambda a: a.next_ts) return result def tick(self, poll=False): '''Signify that one frame has passed. This will call any scheduled functions that have elapsed. :Parameters: `poll` : bool If True, the function will call any scheduled functions but will not sleep or busy-wait for any reason. Recommended for advanced applications managing their own sleep timers only. Since pyglet 1.1. :rtype: float :return: The number of seconds since the last "tick", or 0 if this was the first frame. ''' if poll: if self.period_limit: self.next_ts = self.next_ts + self.period_limit else: if self.period_limit: self._limit() if self._force_sleep: self.sleep(0) delta_t = self.update_time() self.call_scheduled_functions(delta_t) return delta_t def _limit(self): '''Sleep until the next frame is due. Called automatically by `tick` if a framerate limit has been set. This method uses several heuristics to determine whether to sleep or busy-wait (or both). ''' ts = self.time() # Sleep to just before the desired time sleeptime = self.get_sleep_time(False) while sleeptime - self.SLEEP_UNDERSHOOT > self.MIN_SLEEP: self.sleep(1000000 * (sleeptime - self.SLEEP_UNDERSHOOT)) sleeptime = self.get_sleep_time(False) # Busy-loop CPU to get closest to the mark sleeptime = self.next_ts - self.time() while sleeptime > 0: sleeptime = self.next_ts - self.time() if sleeptime < -2 * self.period_limit: # Missed the time by a long shot, let's reset the clock # print >> sys.stderr, 'Step %f' % -sleeptime self.next_ts = ts + 2 * self.period_limit else: # Otherwise keep the clock steady self.next_ts = self.next_ts + self.period_limit def get_sleep_time(self, sleep_idle): '''Get the time until the next item is scheduled. This method considers all scheduled items and the current ``fps_limit``, if any. Applications can choose to continue receiving updates at the maximum framerate during idle time (when no functions are scheduled), or they can sleep through their idle time and allow the CPU to switch to other processes or run in low-power mode. If `sleep_idle` is ``True`` the latter behaviour is selected, and ``None`` will be returned if there are no scheduled items. Otherwise, if `sleep_idle` is ``False``, a sleep time allowing the maximum possible framerate (considering ``fps_limit``) will be returned; or an earlier time if a scheduled function is ready. :Parameters: `sleep_idle` : bool If True, the application intends to sleep through its idle time; otherwise it will continue ticking at the maximum frame rate allowed. :rtype: float :return: Time until the next scheduled event in seconds, or ``None`` if there is no event scheduled. :since: pyglet 1.1 ''' if self._schedule_items or not sleep_idle: if not self.period_limit: return 0. else: wake_time = self.next_ts if self._schedule_interval_items: wake_time = min(wake_time, self._schedule_interval_items[0].next_ts) return max(wake_time - self.time(), 0.) if self._schedule_interval_items: return max(self._schedule_interval_items[0].next_ts - self.time(), 0) return None def set_fps_limit(self, fps_limit): '''Set the framerate limit. The framerate limit applies only when a function is scheduled for every frame. That is, the framerate limit can be exceeded by scheduling a function for a very small period of time. :Parameters: `fps_limit` : float Maximum frames per second allowed, or None to disable limiting. :deprecated: Use `pyglet.app.run` and `schedule_interval` instead. ''' if not fps_limit: self.period_limit = None else: self.period_limit = 1. / fps_limit self.window_size = fps_limit or 60 def get_fps_limit(self): '''Get the framerate limit. :rtype: float :return: The framerate limit previously set in the constructor or `set_fps_limit`, or None if no limit was set. ''' if self.period_limit: return 1. / self.period_limit else: return 0 def get_fps(self): '''Get the average FPS of recent history. The result is the average of a sliding window of the last "n" frames, where "n" is some number designed to cover approximately 1 second. :rtype: float :return: The measured frames per second. ''' if not self.cumulative_time: return 0 return len(self.times) / self.cumulative_time def schedule(self, func, *args, **kwargs): '''Schedule a function to be called every frame. The function should have a prototype that includes ``dt`` as the first argument, which gives the elapsed time, in seconds, since the last clock tick. Any additional arguments given to this function are passed on to the callback:: def callback(dt, *args, **kwargs): pass :Parameters: `func` : function The function to call each frame. ''' item = _ScheduledItem(func, args, kwargs) self._schedule_items.append(item) def _schedule_item(self, func, last_ts, next_ts, interval, *args, **kwargs): item = _ScheduledIntervalItem( func, interval, last_ts, next_ts, args, kwargs) # Insert in sort order for i, other in enumerate(self._schedule_interval_items): if other.next_ts is not None and other.next_ts > next_ts: self._schedule_interval_items.insert(i, item) break else: self._schedule_interval_items.append(item) def schedule_interval(self, func, interval, *args, **kwargs): '''Schedule a function to be called every `interval` seconds. Specifying an interval of 0 prevents the function from being called again (see `schedule` to call a function as often as possible). The callback function prototype is the same as for `schedule`. :Parameters: `func` : function The function to call when the timer lapses. `interval` : float The number of seconds to wait between each call. ''' last_ts = self.last_ts or self.next_ts # Schedule from now, unless now is sufficiently close to last_ts, in # which case use last_ts. This clusters together scheduled items that # probably want to be scheduled together. The old (pre 1.1.1) # behaviour was to always use self.last_ts, and not look at ts. The # new behaviour is needed because clock ticks can now be quite # irregular, and span several seconds. ts = self.time() if ts - last_ts > 0.2: last_ts = ts next_ts = last_ts + interval self._schedule_item(func, last_ts, next_ts, interval, *args, **kwargs) def schedule_interval_soft(self, func, interval, *args, **kwargs): '''Schedule a function to be called every `interval` seconds, beginning at a time that does not coincide with other scheduled events. This method is similar to `schedule_interval`, except that the clock will move the interval out of phase with other scheduled functions so as to distribute CPU more load evenly over time. This is useful for functions that need to be called regularly, but not relative to the initial start time. `pyglet.media` does this for scheduling audio buffer updates, which need to occur regularly -- if all audio updates are scheduled at the same time (for example, mixing several tracks of a music score, or playing multiple videos back simultaneously), the resulting load on the CPU is excessive for those intervals but idle outside. Using the soft interval scheduling, the load is more evenly distributed. Soft interval scheduling can also be used as an easy way to schedule graphics animations out of phase; for example, multiple flags waving in the wind. :since: pyglet 1.1 :Parameters: `func` : function The function to call when the timer lapses. `interval` : float The number of seconds to wait between each call. ''' last_ts = self.last_ts or self.next_ts # See schedule_interval ts = self.time() if ts - last_ts > 0.2: last_ts = ts next_ts = self._get_soft_next_ts(last_ts, interval) last_ts = next_ts - interval self._schedule_item(func, last_ts, next_ts, interval, *args, **kwargs) def _get_soft_next_ts(self, last_ts, interval): def taken(ts, e): '''Return True if the given time has already got an item scheduled nearby. ''' for item in self._schedule_interval_items: if item.next_ts is None: pass elif abs(item.next_ts - ts) <= e: return True elif item.next_ts > ts + e: return False return False # Binary division over interval: # # 0 interval # |--------------------------| # 5 3 6 2 7 4 8 1 Order of search # # i.e., first scheduled at interval, # then at interval/2 # then at interval/4 # then at interval*3/4 # then at ... # # Schedule is hopefully then evenly distributed for any interval, # and any number of scheduled functions. next_ts = last_ts + interval if not taken(next_ts, interval / 4): return next_ts dt = interval divs = 1 while True: next_ts = last_ts for i in range(divs - 1): next_ts += dt if not taken(next_ts, dt / 4): return next_ts dt /= 2 divs *= 2 # Avoid infinite loop in pathological case if divs > 16: return next_ts def schedule_once(self, func, delay, *args, **kwargs): '''Schedule a function to be called once after `delay` seconds. The callback function prototype is the same as for `schedule`. :Parameters: `func` : function The function to call when the timer lapses. `delay` : float The number of seconds to wait before the timer lapses. ''' last_ts = self.last_ts or self.next_ts # See schedule_interval ts = self.time() if ts - last_ts > 0.2: last_ts = ts next_ts = last_ts + delay self._schedule_item(func, last_ts, next_ts, 0, *args, **kwargs) def unschedule(self, func): '''Remove a function from the schedule. If the function appears in the schedule more than once, all occurrences are removed. If the function was not scheduled, no error is raised. :Parameters: `func` : function The function to remove from the schedule. ''' # First replace zombie items' func with a dummy func that does # nothing, in case the list has already been cloned inside tick(). # (Fixes issue 326). for item in self._schedule_items: if item.func == func: item.func = _dummy_schedule_func for item in self._schedule_interval_items: if item.func == func: item.func = _dummy_schedule_func # Now remove matching items from both schedule lists. self._schedule_items = \ [item for item in self._schedule_items \ if item.func is not _dummy_schedule_func] self._schedule_interval_items = \ [item for item in self._schedule_interval_items \ if item.func is not _dummy_schedule_func] # Default clock. _default = Clock() def set_default(default): '''Set the default clock to use for all module-level functions. By default an instance of `Clock` is used. :Parameters: `default` : `Clock` The default clock to use. ''' global _default _default = default def get_default(): '''Return the `Clock` instance that is used by all module-level clock functions. :rtype: `Clock` :return: The default clock. ''' return _default def tick(poll=False): '''Signify that one frame has passed on the default clock. This will call any scheduled functions that have elapsed. :Parameters: `poll` : bool If True, the function will call any scheduled functions but will not sleep or busy-wait for any reason. Recommended for advanced applications managing their own sleep timers only. Since pyglet 1.1. :rtype: float :return: The number of seconds since the last "tick", or 0 if this was the first frame. ''' return _default.tick(poll) def get_sleep_time(sleep_idle): '''Get the time until the next item is scheduled on the default clock. See `Clock.get_sleep_time` for details. :Parameters: `sleep_idle` : bool If True, the application intends to sleep through its idle time; otherwise it will continue ticking at the maximum frame rate allowed. :rtype: float :return: Time until the next scheduled event in seconds, or ``None`` if there is no event scheduled. :since: pyglet 1.1 ''' return _default.get_sleep_time(sleep_idle) def get_fps(): '''Return the current measured FPS of the default clock. :rtype: float ''' return _default.get_fps() def set_fps_limit(fps_limit): '''Set the framerate limit for the default clock. :Parameters: `fps_limit` : float Maximum frames per second allowed, or None to disable limiting. :deprecated: Use `pyglet.app.run` and `schedule_interval` instead. ''' _default.set_fps_limit(fps_limit) def get_fps_limit(): '''Get the framerate limit for the default clock. :return: The framerate limit previously set by `set_fps_limit`, or None if no limit was set. ''' return _default.get_fps_limit() def schedule(func, *args, **kwargs): '''Schedule 'func' to be called every frame on the default clock. The arguments passed to func are ``dt``, followed by any ``*args`` and ``**kwargs`` given here. :Parameters: `func` : function The function to call each frame. ''' _default.schedule(func, *args, **kwargs) def schedule_interval(func, interval, *args, **kwargs): '''Schedule 'func' to be called every 'interval' seconds on the default clock. The arguments passed to 'func' are 'dt' (time since last function call), followed by any ``*args`` and ``**kwargs`` given here. :Parameters: `func` : function The function to call when the timer lapses. `interval` : float The number of seconds to wait between each call. ''' _default.schedule_interval(func, interval, *args, **kwargs) def schedule_interval_soft(func, interval, *args, **kwargs): '''Schedule 'func' to be called every 'interval' seconds on the default clock, beginning at a time that does not coincide with other scheduled events. The arguments passed to 'func' are 'dt' (time since last function call), followed by any ``*args`` and ``**kwargs`` given here. :see: `Clock.schedule_interval_soft` :since: pyglet 1.1 :Parameters: `func` : function The function to call when the timer lapses. `interval` : float The number of seconds to wait between each call. ''' _default.schedule_interval_soft(func, interval, *args, **kwargs) def schedule_once(func, delay, *args, **kwargs): '''Schedule 'func' to be called once after 'delay' seconds (can be a float) on the default clock. The arguments passed to 'func' are 'dt' (time since last function call), followed by any ``*args`` and ``**kwargs`` given here. If no default clock is set, the func is queued and will be scheduled on the default clock as soon as it is created. :Parameters: `func` : function The function to call when the timer lapses. `delay` : float The number of seconds to wait before the timer lapses. ''' _default.schedule_once(func, delay, *args, **kwargs) def unschedule(func): '''Remove 'func' from the default clock's schedule. No error is raised if the func was never scheduled. :Parameters: `func` : function The function to remove from the schedule. ''' _default.unschedule(func) class ClockDisplay(object): '''Display current clock values, such as FPS. This is a convenience class for displaying diagnostics such as the framerate. See the module documentation for example usage. :Ivariables: `label` : `pyglet.font.Text` The label which is displayed. :deprecated: This class presents values that are often misleading, as they reflect the rate of clock ticks, not displayed framerate. Use pyglet.window.FPSDisplay instead. ''' def __init__(self, font=None, interval=0.25, format='%(fps).2f', color=(.5, .5, .5, .5), clock=None): '''Create a ClockDisplay. All parameters are optional. By default, a large translucent font will be used to display the FPS to two decimal places. :Parameters: `font` : `pyglet.font.Font` The font to format text in. `interval` : float The number of seconds between updating the display. `format` : str A format string describing the format of the text. This string is modulated with the dict ``{'fps' : fps}``. `color` : 4-tuple of float The color, including alpha, passed to ``glColor4f``. `clock` : `Clock` The clock which determines the time. If None, the default clock is used. ''' if clock is None: clock = _default self.clock = clock self.clock.schedule_interval(self.update_text, interval) if not font: from pyglet.font import load as load_font font = load_font('', 36, bold=True) import pyglet.font self.label = pyglet.font.Text(font, '', color=color, x=10, y=10) self.format = format def unschedule(self): '''Remove the display from its clock's schedule. `ClockDisplay` uses `Clock.schedule_interval` to periodically update its display label. Even if the ClockDisplay is not being used any more, its update method will still be scheduled, which can be a resource drain. Call this method to unschedule the update method and allow the ClockDisplay to be garbage collected. :since: pyglet 1.1 ''' self.clock.unschedule(self.update_text) def update_text(self, dt=0): '''Scheduled method to update the label text.''' fps = self.clock.get_fps() self.label.text = self.format % {'fps': fps} def draw(self): '''Method called each frame to render the label.''' self.label.draw() def test_clock(): import getopt import sys test_seconds = 1 test_fps = 60 show_fps = False options, args = getopt.getopt(sys.argv[1:], 'vht:f:', ['time=', 'fps=', 'help']) for key, value in options: if key in ('-t', '--time'): test_seconds = float(value) elif key in ('-f', '--fps'): test_fps = float(value) elif key in ('-v'): show_fps = True elif key in ('-h', '--help'): print ('Usage: clock.py <options>\n' '\n' 'Options:\n' ' -t --time Number of seconds to run for.\n' ' -f --fps Target FPS.\n' '\n' 'Tests the clock module by measuring how close we can\n' 'get to the desired FPS by sleeping and busy-waiting.') sys.exit(0) set_fps_limit(test_fps) start = time.time() # Add one because first frame has no update interval. n_frames = int(test_seconds * test_fps + 1) print 'Testing %f FPS for %f seconds...' % (test_fps, test_seconds) for i in xrange(n_frames): tick() if show_fps: print get_fps() total_time = time.time() - start total_error = total_time - test_seconds print 'Total clock error: %f secs' % total_error print 'Total clock error / secs: %f secs/secs' % \ (total_error / test_seconds) # Not fair to add the extra frame in this calc, since no-one's interested # in the startup situation. print 'Average FPS: %f' % ((n_frames - 1) / total_time) if __name__ == '__main__': test_clock()
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id:$ '''Access byte arrays as arrays of vertex attributes. Use `create_attribute` to create an attribute accessor given a simple format string. Alternatively, the classes may be constructed directly. Attribute format strings ======================== An attribute format string specifies the format of a vertex attribute. Format strings are accepted by the `create_attribute` function as well as most methods in the `pyglet.graphics` module. Format strings have the following (BNF) syntax:: attribute ::= ( name | index 'g' 'n'? | texture 't' ) count type ``name`` describes the vertex attribute, and is one of the following constants for the predefined attributes: ``c`` Vertex color ``e`` Edge flag ``f`` Fog coordinate ``n`` Normal vector ``s`` Secondary color ``t`` Texture coordinate ``v`` Vertex coordinate You can alternatively create a generic indexed vertex attribute by specifying its index in decimal followed by the constant ``g``. For example, ``0g`` specifies the generic vertex attribute with index 0. If the optional constant ``n`` is present after the ``g``, the attribute is normalised to the range ``[0, 1]`` or ``[-1, 1]`` within the range of the data type. Texture coordinates for multiple texture units can be specified with the texture number before the constant 't'. For example, ``1t`` gives the texture coordinate attribute for texture unit 1. ``count`` gives the number of data components in the attribute. For example, a 3D vertex position has a count of 3. Some attributes constrain the possible counts that can be used; for example, a normal vector must have a count of 3. ``type`` gives the data type of each component of the attribute. The following types can be used: ``b`` ``GLbyte`` ``B`` ``GLubyte`` ``s`` ``GLshort`` ``S`` ``GLushort`` ``i`` ``GLint`` ``I`` ``GLuint`` ``f`` ``GLfloat`` ``d`` ``GLdouble`` Some attributes constrain the possible data types; for example, normal vectors must use one of the signed data types. The use of some data types, while not illegal, may have severe performance concerns. For example, the use of ``GLdouble`` is discouraged, and colours should be specified with ``GLubyte``. Whitespace is prohibited within the format string. Some examples follow: ``v3f`` 3-float vertex position ``c4b`` 4-byte colour ``1eb`` Edge flag ``0g3f`` 3-float generic vertex attribute 0 ``1gn1i`` Integer generic vertex attribute 1, normalized to [-1, 1] ``2gn4B`` 4-byte generic vertex attribute 2, normalized to [0, 1] (because the type is unsigned) ``3t2f`` 2-float texture coordinate for texture unit 3. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes import re from pyglet.gl import * from pyglet.graphics import vertexbuffer _c_types = { GL_BYTE: ctypes.c_byte, GL_UNSIGNED_BYTE: ctypes.c_ubyte, GL_SHORT: ctypes.c_short, GL_UNSIGNED_SHORT: ctypes.c_ushort, GL_INT: ctypes.c_int, GL_UNSIGNED_INT: ctypes.c_uint, GL_FLOAT: ctypes.c_float, GL_DOUBLE: ctypes.c_double, } _gl_types = { 'b': GL_BYTE, 'B': GL_UNSIGNED_BYTE, 's': GL_SHORT, 'S': GL_UNSIGNED_SHORT, 'i': GL_INT, 'I': GL_UNSIGNED_INT, 'f': GL_FLOAT, 'd': GL_DOUBLE, } _attribute_format_re = re.compile(r''' (?P<name> [cefnstv] | (?P<generic_index>[0-9]+) g (?P<generic_normalized>n?) | (?P<texcoord_texture>[0-9]+) t) (?P<count>[1234]) (?P<type>[bBsSiIfd]) ''', re.VERBOSE) _attribute_cache = {} def _align(v, align): return ((v - 1) & ~(align - 1)) + align def interleave_attributes(attributes): '''Interleave attribute offsets. Adjusts the offsets and strides of the given attributes so that they are interleaved. Alignment constraints are respected. :Parameters: `attributes` : sequence of `AbstractAttribute` Attributes to interleave in-place. ''' stride = 0 max_size = 0 for attribute in attributes: stride = _align(stride, attribute.align) attribute.offset = stride stride += attribute.size max_size = max(max_size, attribute.size) stride = _align(stride, max_size) for attribute in attributes: attribute.stride = stride def serialize_attributes(count, attributes): '''Serialize attribute offsets. Adjust the offsets of the given attributes so that they are packed serially against each other for `count` vertices. :Parameters: `count` : int Number of vertices. `attributes` : sequence of `AbstractAttribute` Attributes to serialize in-place. ''' offset = 0 for attribute in attributes: offset = _align(offset, attribute.align) attribute.offset = offset offset += count * attribute.stride def create_attribute(format): '''Create a vertex attribute description from a format string. The initial stride and offset of the attribute will be 0. :Parameters: `format` : str Attribute format string. See the module summary for details. :rtype: `AbstractAttribute` ''' try: cls, args = _attribute_cache[format] return cls(*args) except KeyError: pass match = _attribute_format_re.match(format) assert match, 'Invalid attribute format %r' % format count = int(match.group('count')) gl_type = _gl_types[match.group('type')] generic_index = match.group('generic_index') texcoord_texture = match.group('texcoord_texture') if generic_index: normalized = match.group('generic_normalized') attr_class = GenericAttribute args = int(generic_index), normalized, count, gl_type elif texcoord_texture: attr_class = MultiTexCoordAttribute args = int(texcoord_texture), count, gl_type else: name = match.group('name') attr_class = _attribute_classes[name] if attr_class._fixed_count: assert count == attr_class._fixed_count, \ 'Attributes named "%s" must have count of %d' % ( name, attr_class._fixed_count) args = (gl_type,) else: args = (count, gl_type) _attribute_cache[format] = attr_class, args return attr_class(*args) class AbstractAttribute(object): '''Abstract accessor for an attribute in a mapped buffer. ''' _fixed_count = None def __init__(self, count, gl_type): '''Create the attribute accessor. :Parameters: `count` : int Number of components in the attribute. `gl_type` : int OpenGL type enumerant; for example, ``GL_FLOAT`` ''' assert count in (1, 2, 3, 4), 'Component count out of range' self.gl_type = gl_type self.c_type = _c_types[gl_type] self.count = count self.align = ctypes.sizeof(self.c_type) self.size = count * self.align self.stride = self.size self.offset = 0 def enable(self): '''Enable the attribute using ``glEnableClientState``.''' raise NotImplementedError('abstract') def set_pointer(self, offset): '''Setup this attribute to point to the currently bound buffer at the given offset. ``offset`` should be based on the currently bound buffer's ``ptr`` member. :Parameters: `offset` : int Pointer offset to the currently bound buffer for this attribute. ''' raise NotImplementedError('abstract') def get_region(self, buffer, start, count): '''Map a buffer region using this attribute as an accessor. The returned region can be modified as if the buffer was a contiguous array of this attribute (though it may actually be interleaved or otherwise non-contiguous). The returned region consists of a contiguous array of component data elements. For example, if this attribute uses 3 floats per vertex, and the `count` parameter is 4, the number of floats mapped will be ``3 * 4 = 12``. :Parameters: `buffer` : `AbstractMappable` The buffer to map. `start` : int Offset of the first vertex to map. `count` : int Number of vertices to map :rtype: `AbstractBufferRegion` ''' byte_start = self.stride * start byte_size = self.stride * count array_count = self.count * count if self.stride == self.size or not array_count: # non-interleaved ptr_type = ctypes.POINTER(self.c_type * array_count) return buffer.get_region(byte_start, byte_size, ptr_type) else: # interleaved byte_start += self.offset byte_size -= self.offset elem_stride = self.stride // ctypes.sizeof(self.c_type) elem_offset = self.offset // ctypes.sizeof(self.c_type) ptr_type = ctypes.POINTER( self.c_type * (count * elem_stride - elem_offset)) region = buffer.get_region(byte_start, byte_size, ptr_type) return vertexbuffer.IndirectArrayRegion( region, array_count, self.count, elem_stride) def set_region(self, buffer, start, count, data): '''Set the data over a region of the buffer. :Parameters: `buffer` : AbstractMappable` The buffer to modify. `start` : int Offset of the first vertex to set. `count` : int Number of vertices to set. `data` : sequence Sequence of data components. ''' if self.stride == self.size: # non-interleaved byte_start = self.stride * start byte_size = self.stride * count array_count = self.count * count data = (self.c_type * array_count)(*data) buffer.set_data_region(data, byte_start, byte_size) else: # interleaved region = self.get_region(buffer, start, count) region[:] = data class ColorAttribute(AbstractAttribute): '''Color vertex attribute.''' plural = 'colors' def __init__(self, count, gl_type): assert count in (3, 4), 'Color attributes must have count of 3 or 4' super(ColorAttribute, self).__init__(count, gl_type) def enable(self): glEnableClientState(GL_COLOR_ARRAY) def set_pointer(self, pointer): glColorPointer(self.count, self.gl_type, self.stride, self.offset + pointer) class EdgeFlagAttribute(AbstractAttribute): '''Edge flag attribute.''' plural = 'edge_flags' _fixed_count = 1 def __init__(self, gl_type): assert gl_type in (GL_BYTE, GL_UNSIGNED_BYTE, GL_BOOL), \ 'Edge flag attribute must have boolean type' super(EdgeFlagAttribute, self).__init__(1, gl_type) def enable(self): glEnableClientState(GL_EDGE_FLAG_ARRAY) def set_pointer(self, pointer): glEdgeFlagPointer(self.stride, self.offset + pointer) class FogCoordAttribute(AbstractAttribute): '''Fog coordinate attribute.''' plural = 'fog_coords' def __init__(self, count, gl_type): super(FogCoordAttribute, self).__init__(count, gl_type) def enable(self): glEnableClientState(GL_FOG_COORD_ARRAY) def set_pointer(self, pointer): glFogCoordPointer(self.count, self.gl_type, self.stride, self.offset + pointer) class NormalAttribute(AbstractAttribute): '''Normal vector attribute.''' plural = 'normals' _fixed_count = 3 def __init__(self, gl_type): assert gl_type in (GL_BYTE, GL_SHORT, GL_INT, GL_FLOAT, GL_DOUBLE), \ 'Normal attribute must have signed type' super(NormalAttribute, self).__init__(3, gl_type) def enable(self): glEnableClientState(GL_NORMAL_ARRAY) def set_pointer(self, pointer): glNormalPointer(self.gl_type, self.stride, self.offset + pointer) class SecondaryColorAttribute(AbstractAttribute): '''Secondary color attribute.''' plural = 'secondary_colors' _fixed_count = 3 def __init__(self, gl_type): super(SecondaryColorAttribute, self).__init__(3, gl_type) def enable(self): glEnableClientState(GL_SECONDARY_COLOR_ARRAY) def set_pointer(self, pointer): glSecondaryColorPointer(3, self.gl_type, self.stride, self.offset + pointer) class TexCoordAttribute(AbstractAttribute): '''Texture coordinate attribute.''' plural = 'tex_coords' def __init__(self, count, gl_type): assert gl_type in (GL_SHORT, GL_INT, GL_INT, GL_FLOAT, GL_DOUBLE), \ 'Texture coord attribute must have non-byte signed type' super(TexCoordAttribute, self).__init__(count, gl_type) def enable(self): glEnableClientState(GL_TEXTURE_COORD_ARRAY) def set_pointer(self, pointer): glTexCoordPointer(self.count, self.gl_type, self.stride, self.offset + pointer) def convert_to_multi_tex_coord_attribute(self): '''Changes the class of the attribute to `MultiTexCoordAttribute`. ''' self.__class__ = MultiTexCoordAttribute self.texture = 0 class MultiTexCoordAttribute(AbstractAttribute): '''Texture coordinate attribute.''' def __init__(self, texture, count, gl_type): assert gl_type in (GL_SHORT, GL_INT, GL_INT, GL_FLOAT, GL_DOUBLE), \ 'Texture coord attribute must have non-byte signed type' self.texture = texture super(MultiTexCoordAttribute, self).__init__(count, gl_type) def enable(self): glClientActiveTexture(GL_TEXTURE0 + self.texture) glEnableClientState(GL_TEXTURE_COORD_ARRAY) def set_pointer(self, pointer): glTexCoordPointer(self.count, self.gl_type, self.stride, self.offset + pointer) class VertexAttribute(AbstractAttribute): '''Vertex coordinate attribute.''' plural = 'vertices' def __init__(self, count, gl_type): assert count > 1, \ 'Vertex attribute must have count of 2, 3 or 4' assert gl_type in (GL_SHORT, GL_INT, GL_INT, GL_FLOAT, GL_DOUBLE), \ 'Vertex attribute must have signed type larger than byte' super(VertexAttribute, self).__init__(count, gl_type) def enable(self): glEnableClientState(GL_VERTEX_ARRAY) def set_pointer(self, pointer): glVertexPointer(self.count, self.gl_type, self.stride, self.offset + pointer) class GenericAttribute(AbstractAttribute): '''Generic vertex attribute, used by shader programs.''' def __init__(self, index, normalized, count, gl_type): self.normalized = bool(normalized) self.index = index super(GenericAttribute, self).__init__(count, gl_type) def enable(self): glEnableVertexAttribArray(self.index) def set_pointer(self, pointer): glVertexAttribPointer(self.index, self.count, self.gl_type, self.normalized, self.stride, self.offset + pointer) _attribute_classes = { 'c': ColorAttribute, 'e': EdgeFlagAttribute, 'f': FogCoordAttribute, 'n': NormalAttribute, 's': SecondaryColorAttribute, 't': TexCoordAttribute, 'v': VertexAttribute, }
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id:$ '''Byte abstractions of Vertex Buffer Objects and vertex arrays. Use `create_buffer` or `create_mappable_buffer` to create a Vertex Buffer Object, or a vertex array if VBOs are not supported by the current context. Buffers can optionally be created "mappable" (incorporating the `AbstractMappable` mix-in). In this case the buffer provides a ``get_region`` method which provides the most efficient path for updating partial data within the buffer. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes import sys import pyglet from pyglet.gl import * _enable_vbo = pyglet.options['graphics_vbo'] # Enable workaround permanently if any VBO is created on a context that has # this workaround. (On systems with multiple contexts where one is # unaffected, the workaround will be enabled unconditionally on all of the # contexts anyway. This is completely unlikely anyway). _workaround_vbo_finish = False def create_buffer(size, target=GL_ARRAY_BUFFER, usage=GL_DYNAMIC_DRAW, vbo=True): '''Create a buffer of vertex data. :Parameters: `size` : int Size of the buffer, in bytes `target` : int OpenGL target buffer `usage` : int OpenGL usage constant `vbo` : bool True if a `VertexBufferObject` should be created if the driver supports it; otherwise only a `VertexArray` is created. :rtype: `AbstractBuffer` ''' from pyglet import gl if (vbo and gl_info.have_version(1, 5) and _enable_vbo and not gl.current_context._workaround_vbo): return VertexBufferObject(size, target, usage) else: return VertexArray(size) def create_mappable_buffer(size, target=GL_ARRAY_BUFFER, usage=GL_DYNAMIC_DRAW, vbo=True): '''Create a mappable buffer of vertex data. :Parameters: `size` : int Size of the buffer, in bytes `target` : int OpenGL target buffer `usage` : int OpenGL usage constant `vbo` : bool True if a `VertexBufferObject` should be created if the driver supports it; otherwise only a `VertexArray` is created. :rtype: `AbstractBuffer` with `AbstractMappable` ''' from pyglet import gl if (vbo and gl_info.have_version(1, 5) and _enable_vbo and not gl.current_context._workaround_vbo): return MappableVertexBufferObject(size, target, usage) else: return VertexArray(size) class AbstractBuffer(object): '''Abstract buffer of byte data. :Ivariables: `size` : int Size of buffer, in bytes `ptr` : int Memory offset of the buffer, as used by the ``glVertexPointer`` family of functions `target` : int OpenGL buffer target, for example ``GL_ARRAY_BUFFER`` `usage` : int OpenGL buffer usage, for example ``GL_DYNAMIC_DRAW`` ''' ptr = 0 size = 0 def bind(self): '''Bind this buffer to its OpenGL target.''' raise NotImplementedError('abstract') def unbind(self): '''Reset the buffer's OpenGL target.''' raise NotImplementedError('abstract') def set_data(self, data): '''Set the entire contents of the buffer. :Parameters: `data` : sequence of int or ctypes pointer The byte array to set. ''' raise NotImplementedError('abstract') def set_data_region(self, data, start, length): '''Set part of the buffer contents. :Parameters: `data` : sequence of int or ctypes pointer The byte array of data to set `start` : int Offset to start replacing data `length` : int Length of region to replace ''' raise NotImplementedError('abstract') def map(self, invalidate=False): '''Map the entire buffer into system memory. The mapped region must be subsequently unmapped with `unmap` before performing any other operations on the buffer. :Parameters: `invalidate` : bool If True, the initial contents of the mapped block need not reflect the actual contents of the buffer. :rtype: ``POINTER(ctypes.c_ubyte)`` :return: Pointer to the mapped block in memory ''' raise NotImplementedError('abstract') def unmap(self): '''Unmap a previously mapped memory block.''' raise NotImplementedError('abstract') def resize(self, size): '''Resize the buffer to a new size. :Parameters: `size` : int New size of the buffer, in bytes ''' def delete(self): '''Delete this buffer, reducing system resource usage.''' raise NotImplementedError('abstract') class AbstractMappable(object): def get_region(self, start, size, ptr_type): '''Map a region of the buffer into a ctypes array of the desired type. This region does not need to be unmapped, but will become invalid if the buffer is resized. Note that although a pointer type is required, an array is mapped. For example:: get_region(0, ctypes.sizeof(c_int) * 20, ctypes.POINTER(c_int * 20)) will map bytes 0 to 80 of the buffer to an array of 20 ints. Changes to the array may not be recognised until the region's `AbstractBufferRegion.invalidate` method is called. :Parameters: `start` : int Offset into the buffer to map from, in bytes `size` : int Size of the buffer region to map, in bytes `ptr_type` : ctypes pointer type Pointer type describing the array format to create :rtype: `AbstractBufferRegion` ''' raise NotImplementedError('abstract') class VertexArray(AbstractBuffer, AbstractMappable): '''A ctypes implementation of a vertex array. Many of the methods on this class are effectively no-op's, such as `bind`, `unbind`, `map`, `unmap` and `delete`; they exist in order to present a consistent interface with `VertexBufferObject`. This buffer type is also mappable, and so `get_region` can be used. ''' def __init__(self, size): self.size = size self.array = (ctypes.c_byte * size)() self.ptr = ctypes.cast(self.array, ctypes.c_void_p).value def bind(self): pass def unbind(self): pass def set_data(self, data): ctypes.memmove(self.ptr, data, self.size) def set_data_region(self, data, start, length): ctypes.memmove(self.ptr + start, data, length) def map(self, invalidate=False): return self.array def unmap(self): pass def get_region(self, start, size, ptr_type): array = ctypes.cast(self.ptr + start, ptr_type).contents return VertexArrayRegion(array) def delete(self): pass def resize(self, size): array = (ctypes.c_byte * size)() ctypes.memmove(array, self.array, min(size, self.size)) self.size = size self.array = array self.ptr = ctypes.cast(self.array, ctypes.c_void_p).value class VertexBufferObject(AbstractBuffer): '''Lightweight representation of an OpenGL VBO. The data in the buffer is not replicated in any system memory (unless it is done so by the video driver). While this can improve memory usage and possibly performance, updates to the buffer are relatively slow. This class does not implement `AbstractMappable`, and so has no ``get_region`` method. See `MappableVertexBufferObject` for a VBO class that does implement ``get_region``. ''' def __init__(self, size, target, usage): self.size = size self.target = target self.usage = usage self._context = pyglet.gl.current_context id = GLuint() glGenBuffers(1, id) self.id = id.value glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glBindBuffer(target, self.id) glBufferData(target, self.size, None, self.usage) glPopClientAttrib() global _workaround_vbo_finish if pyglet.gl.current_context._workaround_vbo_finish: _workaround_vbo_finish = True def bind(self): glBindBuffer(self.target, self.id) def unbind(self): glBindBuffer(self.target, 0) def set_data(self, data): glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glBindBuffer(self.target, self.id) glBufferData(self.target, self.size, data, self.usage) glPopClientAttrib() def set_data_region(self, data, start, length): glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glBindBuffer(self.target, self.id) glBufferSubData(self.target, start, length, data) glPopClientAttrib() def map(self, invalidate=False): glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glBindBuffer(self.target, self.id) if invalidate: glBufferData(self.target, self.size, None, self.usage) ptr = ctypes.cast(glMapBuffer(self.target, GL_WRITE_ONLY), ctypes.POINTER(ctypes.c_byte * self.size)).contents glPopClientAttrib() return ptr def unmap(self): glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glUnmapBuffer(self.target) glPopClientAttrib() def __del__(self): try: if self.id is not None: self._context.delete_buffer(self.id) except: pass def delete(self): id = GLuint(self.id) glDeleteBuffers(1, id) self.id = None def resize(self, size): # Map, create a copy, then reinitialize. temp = (ctypes.c_byte * size)() glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glBindBuffer(self.target, self.id) data = glMapBuffer(self.target, GL_READ_ONLY) ctypes.memmove(temp, data, min(size, self.size)) glUnmapBuffer(self.target) self.size = size glBufferData(self.target, self.size, temp, self.usage) glPopClientAttrib() class MappableVertexBufferObject(VertexBufferObject, AbstractMappable): '''A VBO with system-memory backed store. Updates to the data via `set_data`, `set_data_region` and `map` will be held in local memory until `bind` is called. The advantage is that fewer OpenGL calls are needed, increasing performance. There may also be less performance penalty for resizing this buffer. Updates to data via `map` are committed immediately. ''' def __init__(self, size, target, usage): super(MappableVertexBufferObject, self).__init__(size, target, usage) self.data = (ctypes.c_byte * size)() self.data_ptr = ctypes.cast(self.data, ctypes.c_void_p).value self._dirty_min = sys.maxint self._dirty_max = 0 def bind(self): # Commit pending data super(MappableVertexBufferObject, self).bind() size = self._dirty_max - self._dirty_min if size > 0: if size == self.size: glBufferData(self.target, self.size, self.data, self.usage) else: glBufferSubData(self.target, self._dirty_min, size, self.data_ptr + self._dirty_min) self._dirty_min = sys.maxint self._dirty_max = 0 def set_data(self, data): super(MappableVertexBufferObject, self).set_data(data) ctypes.memmove(self.data, data, self.size) self._dirty_min = 0 self._dirty_max = self.size def set_data_region(self, data, start, length): ctypes.memmove(self.data_ptr + start, data, length) self._dirty_min = min(start, self._dirty_min) self._dirty_max = max(start + length, self._dirty_max) def map(self, invalidate=False): self._dirty_min = 0 self._dirty_max = self.size return self.data def unmap(self): pass def get_region(self, start, size, ptr_type): array = ctypes.cast(self.data_ptr + start, ptr_type).contents return VertexBufferObjectRegion(self, start, start + size, array) def resize(self, size): data = (ctypes.c_byte * size)() ctypes.memmove(data, self.data, min(size, self.size)) self.data = data self.data_ptr = ctypes.cast(self.data, ctypes.c_void_p).value self.size = size glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glBindBuffer(self.target, self.id) glBufferData(self.target, self.size, self.data, self.usage) glPopClientAttrib() self._dirty_min = sys.maxint self._dirty_max = 0 class AbstractBufferRegion(object): '''A mapped region of a buffer. Buffer regions are obtained using `AbstractMappable.get_region`. :Ivariables: `array` : ctypes array Array of data, of the type and count requested by ``get_region``. ''' def invalidate(self): '''Mark this region as changed. The buffer may not be updated with the latest contents of the array until this method is called. (However, it may not be updated until the next time the buffer is used, for efficiency). ''' pass class VertexBufferObjectRegion(AbstractBufferRegion): '''A mapped region of a VBO.''' def __init__(self, buffer, start, end, array): self.buffer = buffer self.start = start self.end = end self.array = array def invalidate(self): buffer = self.buffer buffer._dirty_min = min(buffer._dirty_min, self.start) buffer._dirty_max = max(buffer._dirty_max, self.end) class VertexArrayRegion(AbstractBufferRegion): '''A mapped region of a vertex array. The `invalidate` method is a no-op but is provided in order to present a consistent interface with `VertexBufferObjectRegion`. ''' def __init__(self, array): self.array = array class IndirectArrayRegion(AbstractBufferRegion): '''A mapped region in which data elements are not necessarily contiguous. This region class is used to wrap buffer regions in which the data must be accessed with some stride. For example, in an interleaved buffer this region can be used to access a single interleaved component as if the data was contiguous. ''' def __init__(self, region, size, component_count, component_stride): '''Wrap a buffer region. Use the `component_count` and `component_stride` parameters to specify the data layout of the encapsulated region. For example, if RGBA data is to be accessed as if it were packed RGB, ``component_count`` would be set to 3 and ``component_stride`` to 4. If the region contains 10 RGBA tuples, the ``size`` parameter is ``3 * 10 = 30``. :Parameters: `region` : `AbstractBufferRegion` The region with interleaved data `size` : int The number of elements that this region will provide access to. `component_count` : int The number of elements that are contiguous before some must be skipped. `component_stride` : int The number of elements of interleaved data separating the contiguous sections. ''' self.region = region self.size = size self.count = component_count self.stride = component_stride self.array = self def __repr__(self): return 'IndirectArrayRegion(size=%d, count=%d, stride=%d)' % ( self.size, self.count, self.stride) def __getitem__(self, index): count = self.count if not isinstance(index, slice): elem = index // count j = index % count return self.region.array[elem * self.stride + j] start = index.start or 0 stop = index.stop step = index.step or 1 if start < 0: start = self.size + start if stop is None: stop = self.size elif stop < 0: stop = self.size + stop assert step == 1 or step % count == 0, \ 'Step must be multiple of component count' data_start = (start // count) * self.stride + start % count data_stop = (stop // count) * self.stride + stop % count data_step = step * self.stride # TODO stepped getitem is probably wrong, see setitem for correct. value_step = step * count # ctypes does not support stepped slicing, so do the work in a list # and copy it back. data = self.region.array[:] value = [0] * ((stop - start) // step) stride = self.stride for i in range(count): value[i::value_step] = \ data[data_start + i:data_stop + i:data_step] return value def __setitem__(self, index, value): count = self.count if not isinstance(index, slice): elem = index // count j = index % count self.region.array[elem * self.stride + j] = value return start = index.start or 0 stop = index.stop step = index.step or 1 if start < 0: start = self.size + start if stop is None: stop = self.size elif stop < 0: stop = self.size + stop assert step == 1 or step % count == 0, \ 'Step must be multiple of component count' data_start = (start // count) * self.stride + start % count data_stop = (stop // count) * self.stride + stop % count # ctypes does not support stepped slicing, so do the work in a list # and copy it back. data = self.region.array[:] if step == 1: data_step = self.stride value_step = count for i in range(count): data[data_start + i:data_stop + i:data_step] = \ value[i::value_step] else: data_step = (step // count) * self.stride data[data_start:data_stop:data_step] = value self.region.array[:] = data def invalidate(self): self.region.invalidate()
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id:$ '''Memory allocation algorithm for vertex arrays and buffers. The region allocator is used to allocate vertex indices within a vertex domain's multiple buffers. ("Buffer" refers to any abstract buffer presented by `pyglet.graphics.vertexbuffer`. The allocator will at times request more space from the buffers. The current policy is to double the buffer size when there is not enough room to fulfil an allocation. The buffer is never resized smaller. The allocator maintains references to free space only; it is the caller's responsibility to maintain the allocated regions. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' # Common cases: # -regions will be the same size (instances of same object, e.g. sprites) # -regions will not usually be resized (only exception is text) # -alignment of 4 vertices (glyphs, sprites, images, ...) # # Optimise for: # -keeping regions adjacent, reduce the number of entries in glMultiDrawArrays # -finding large blocks of allocated regions quickly (for drawing) # -finding block of unallocated space is the _uncommon_ case! # # Decisions: # -don't over-allocate regions to any alignment -- this would require more # work in finding the allocated spaces (for drawing) and would result in # more entries in glMultiDrawArrays # -don't move blocks when they truncate themselves. try not to allocate the # space they freed too soon (they will likely need grow back into it later, # and growing will usually require a reallocation). # -allocator does not track individual allocated regions. Trusts caller # to provide accurate (start, size) tuple, which completely describes # a region from the allocator's point of view. # -this means that compacting is probably not feasible, or would be hideously # expensive class AllocatorMemoryException(Exception): '''The buffer is not large enough to fulfil an allocation. Raised by `Allocator` methods when the operation failed due to lack of buffer space. The buffer should be increased to at least requested_capacity and then the operation retried (guaranteed to pass second time). ''' def __init__(self, requested_capacity): self.requested_capacity = requested_capacity class Allocator(object): '''Buffer space allocation implementation.''' def __init__(self, capacity): '''Create an allocator for a buffer of the specified capacity. :Parameters: `capacity` : int Maximum size of the buffer. ''' self.capacity = capacity # Allocated blocks. Start index and size in parallel lists. # # # = allocated, - = free # # 0 3 5 15 20 24 40 # |###--##########-----####----------------------| # # starts = [0, 5, 20] # sizes = [3, 10, 4] # # To calculate free blocks: # for i in range(0, len(starts)): # free_start[i] = starts[i] + sizes[i] # free_size[i] = starts[i+1] - free_start[i] # free_size[i+1] = self.capacity - free_start[-1] self.starts = [] self.sizes = [] def set_capacity(self, size): '''Resize the maximum buffer size. The capaity cannot be reduced. :Parameters: `size` : int New maximum size of the buffer. ''' assert size > self.capacity self.capacity = size def alloc(self, size): '''Allocate memory in the buffer. Raises `AllocatorMemoryException` if the allocation cannot be fulfilled. :Parameters: `size` : int Size of region to allocate. :rtype: int :return: Starting index of the allocated region. ''' assert size >= 0 if size == 0: return 0 # return start # or raise AllocatorMemoryException if not self.starts: if size <= self.capacity: self.starts.append(0) self.sizes.append(size) return 0 else: raise AllocatorMemoryException(size) # Allocate in a free space free_start = self.starts[0] + self.sizes[0] for i, (alloc_start, alloc_size) in \ enumerate(zip(self.starts[1:], self.sizes[1:])): # Danger! # i is actually index - 1 because of slicing above... # starts[i] points to the block before this free space # starts[i+1] points to the block after this free space, and is # always valid. free_size = alloc_start - free_start if free_size == size: # Merge previous block with this one (removing this free space) self.sizes[i] += free_size + alloc_size del self.starts[i+1] del self.sizes[i+1] return free_start elif free_size > size: # Increase size of previous block to intrude into this free # space. self.sizes[i] += size return free_start free_start = alloc_start + alloc_size # Allocate at end of capacity free_size = self.capacity - free_start if free_size >= size: self.sizes[-1] += size return free_start raise AllocatorMemoryException(self.capacity + size - free_size) def realloc(self, start, size, new_size): '''Reallocate a region of the buffer. This is more efficient than separate `dealloc` and `alloc` calls, as the region can often be resized in-place. Raises `AllocatorMemoryException` if the allocation cannot be fulfilled. :Parameters: `start` : int Current starting index of the region. `size` : int Current size of the region. `new_size` : int New size of the region. ''' assert size >= 0 and new_size >= 0 if new_size == 0: if size != 0: self.dealloc(start, size) return 0 elif size == 0: return self.alloc(new_size) # return start # or raise AllocatorMemoryException # Truncation is the same as deallocating the tail cruft if new_size < size: self.dealloc(start + new_size, size - new_size) return start # Find which block it lives in for i, (alloc_start, alloc_size) in \ enumerate(zip(*(self.starts, self.sizes))): p = start - alloc_start if p >= 0 and size <= alloc_size - p: break if not (p >= 0 and size <= alloc_size - p): print zip(self.starts, self.sizes) print start, size, new_size print p, alloc_start, alloc_size assert p >= 0 and size <= alloc_size - p, 'Region not allocated' if size == alloc_size - p: # Region is at end of block. Find how much free space is after # it. is_final_block = i == len(self.starts) - 1 if not is_final_block: free_size = self.starts[i + 1] - (start + size) else: free_size = self.capacity - (start + size) # TODO If region is an entire block being an island in free space, # can possibly extend in both directions. if free_size == new_size - size and not is_final_block: # Merge block with next (region is expanded in place to # exactly fill the free space) self.sizes[i] += free_size + self.sizes[i + 1] del self.starts[i + 1] del self.sizes[i + 1] return start elif free_size > new_size - size: # Expand region in place self.sizes[i] += new_size - size return start # The block must be repositioned. Dealloc then alloc. # But don't do this! If alloc fails, we've already silently dealloc'd # the original block. # self.dealloc(start, size) # return self.alloc(new_size) # It must be alloc'd first. We're not missing an optimisation # here, because if freeing the block would've allowed for the block to # be placed in the resulting free space, one of the above in-place # checks would've found it. result = self.alloc(new_size) self.dealloc(start, size) return result def dealloc(self, start, size): '''Free a region of the buffer. :Parameters: `start` : int Starting index of the region. `size` : int Size of the region. ''' assert size >= 0 if size == 0: return assert self.starts # Find which block needs to be split for i, (alloc_start, alloc_size) in \ enumerate(zip(*(self.starts, self.sizes))): p = start - alloc_start if p >= 0 and size <= alloc_size - p: break # Assert we left via the break assert p >= 0 and size <= alloc_size - p, 'Region not allocated' if p == 0 and size == alloc_size: # Remove entire block del self.starts[i] del self.sizes[i] elif p == 0: # Truncate beginning of block self.starts[i] += size self.sizes[i] -= size elif size == alloc_size - p: # Truncate end of block self.sizes[i] -= size else: # Reduce size of left side, insert block at right side # $ = dealloc'd block, # = alloc'd region from same block # # <------8------> # <-5-><-6-><-7-> # 1 2 3 4 # #####$$$$$##### # # 1 = alloc_start # 2 = start # 3 = start + size # 4 = alloc_start + alloc_size # 5 = start - alloc_start = p # 6 = size # 7 = {8} - ({5} + {6}) = alloc_size - (p + size) # 8 = alloc_size # self.sizes[i] = p self.starts.insert(i + 1, start + size) self.sizes.insert(i + 1, alloc_size - (p + size)) def get_allocated_regions(self): '''Get a list of (aggregate) allocated regions. The result of this method is ``(starts, sizes)``, where ``starts`` is a list of starting indices of the regions and ``sizes`` their corresponding lengths. :rtype: (list, list) ''' # return (starts, sizes); len(starts) == len(sizes) return (self.starts, self.sizes) def get_fragmented_free_size(self): '''Returns the amount of space unused, not including the final free block. :rtype: int ''' if not self.starts: return 0 # Variation of search for free block. total_free = 0 free_start = self.starts[0] + self.sizes[0] for i, (alloc_start, alloc_size) in \ enumerate(zip(self.starts[1:], self.sizes[1:])): total_free += alloc_start - free_start free_start = alloc_start + alloc_size return total_free def get_free_size(self): '''Return the amount of space unused. :rtype: int ''' if not self.starts: return self.capacity free_end = self.capacity - (self.starts[-1] + self.sizes[-1]) return self.get_fragmented_free_size() + free_end def get_usage(self): '''Return fraction of capacity currently allocated. :rtype: float ''' return 1. - self.get_free_size() / float(self.capacity) def get_fragmentation(self): '''Return fraction of free space that is not expandable. :rtype: float ''' free_size = self.get_free_size() if free_size == 0: return 0. return self.get_fragmented_free_size() / float(self.get_free_size()) def _is_empty(self): return not self.starts def __str__(self): return 'allocs=' + repr(zip(self.starts, self.sizes)) def __repr__(self): return '<%s %s>' % (self.__class__.__name__, str(self))
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id:$ '''Low-level graphics rendering. This module provides an efficient low-level abstraction over OpenGL. It gives very good performance for rendering OpenGL primitives; far better than the typical immediate-mode usage and, on modern graphics cards, better than using display lists in many cases. The module is used internally by other areas of pyglet. See the Programming Guide for details on how to use this graphics API. Batches and groups ================== Without even needing to understand the details on how to draw primitives with the graphics API, developers can make use of `Batch` and `Group` objects to improve performance of sprite and text rendering. The `Sprite`, `Label` and `TextLayout` classes all accept a ``batch`` and ``group`` parameter in their constructors. A batch manages a set of objects that will be drawn all at once, and a group describes the manner in which an object is drawn. The following example creates a batch, adds two sprites to the batch, and then draws the entire batch:: batch = pyglet.graphics.Batch() car = pyglet.sprite.Sprite(car_image, batch=batch) boat = pyglet.sprite.Sprite(boat_image, batch=batch) def on_draw() batch.draw() Drawing a complete batch is much faster than drawing the items in the batch individually, especially when those items belong to a common group. Groups describe the OpenGL state required for an item. This is for the most part managed by the sprite and text classes, however you can also use groups to ensure items are drawn in a particular order. For example, the following example adds a background sprite which is guaranteed to be drawn before the car and the boat:: batch = pyglet.graphics.Batch() background = pyglet.graphics.OrderedGroup(0) foreground = pyglet.graphics.OrderedGroup(1) background = pyglet.sprite.Sprite(background_image, batch=batch, group=background) car = pyglet.sprite.Sprite(car_image, batch=batch, group=foreground) boat = pyglet.sprite.Sprite(boat_image, batch=batch, group=foreground) def on_draw() batch.draw() It's preferable to manage sprites and text objects within as few batches as possible. If the drawing of sprites or text objects need to be interleaved with other drawing that does not use the graphics API, multiple batches will be required. Data item parameters ==================== Many of the functions and methods in this module accept any number of ``data`` parameters as their final parameters. In the documentation these are notated as ``*data`` in the formal parameter list. A data parameter describes a vertex attribute format and an optional sequence to initialise that attribute. Examples of common attribute formats are: ``"v3f"`` Vertex position, specified as three floats. ``"c4B"`` Vertex color, specified as four unsigned bytes. ``"t2f"`` Texture coordinate, specified as two floats. See `pyglet.graphics.vertexattribute` for the complete syntax of the vertex format string. When no initial data is to be given, the data item is just the format string. For example, the following creates a 2 element vertex list with position and color attributes:: vertex_list = pyglet.graphics.vertex_list(2, 'v2f', 'c4B') When initial data is required, wrap the format string and the initial data in a tuple, for example:: vertex_list = pyglet.graphics.vertex_list(2, ('v2f', (0.0, 1.0, 1.0, 0.0)), ('c4B', (255, 255, 255, 255) * 2)) Drawing modes ============= Methods in this module that accept a ``mode`` parameter will accept any value in the OpenGL drawing mode enumeration: ``GL_POINTS``, ``GL_LINE_STRIP``, ``GL_LINE_LOOP``, ``GL_LINES``, ``GL_TRIANGLE_STRIP``, ``GL_TRIANGLE_FAN``, ``GL_TRIANGLES``, ``GL_QUAD_STRIP``, ``GL_QUADS``, and ``GL_POLYGON``. :: pyglet.graphics.draw(1, GL_POINTS, ('v2i',(10,20))) However, because of the way the graphics API renders multiple primitives with shared state, ``GL_POLYGON``, ``GL_LINE_LOOP`` and ``GL_TRIANGLE_FAN`` cannot be used --- the results are undefined. When using ``GL_LINE_STRIP``, ``GL_TRIANGLE_STRIP`` or ``GL_QUAD_STRIP`` care must be taken to insert degenerate vertices at the beginning and end of each vertex list. For example, given the vertex list:: A, B, C, D the correct vertex list to provide the vertex list is:: A, A, B, C, D, D Alternatively, the ``NV_primitive_restart`` extension can be used if it is present. This also permits use of ``GL_POLYGON``, ``GL_LINE_LOOP`` and ``GL_TRIANGLE_FAN``. Unfortunately the extension is not provided by older video drivers, and requires indexed vertex lists. :since: pyglet 1.1 ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes import pyglet from pyglet.gl import * from pyglet import gl from pyglet.graphics import vertexbuffer, vertexattribute, vertexdomain _debug_graphics_batch = pyglet.options['debug_graphics_batch'] def draw(size, mode, *data): '''Draw a primitive immediately. :Parameters: `size` : int Number of vertices given `mode` : gl primitive type OpenGL drawing mode, e.g. ``GL_TRIANGLES``, avoiding quotes. `data` : data items Attribute formats and data. See the module summary for details. ''' glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) buffers = [] for format, array in data: attribute = vertexattribute.create_attribute(format) assert size == len(array) // attribute.count, \ 'Data for %s is incorrect length' % format buffer = vertexbuffer.create_mappable_buffer( size * attribute.stride, vbo=False) attribute.set_region(buffer, 0, size, array) attribute.enable() attribute.set_pointer(buffer.ptr) buffers.append(buffer) glDrawArrays(mode, 0, size) glFlush() glPopClientAttrib() def draw_indexed(size, mode, indices, *data): '''Draw a primitive with indexed vertices immediately. :Parameters: `size` : int Number of vertices given `mode` : int OpenGL drawing mode, e.g. ``GL_TRIANGLES`` `indices` : sequence of int Sequence of integers giving indices into the vertex list. `data` : data items Attribute formats and data. See the module summary for details. ''' glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) buffers = [] for format, array in data: attribute = vertexattribute.create_attribute(format) assert size == len(array) // attribute.count, \ 'Data for %s is incorrect length' % format buffer = vertexbuffer.create_mappable_buffer( size * attribute.stride, vbo=False) attribute.set_region(buffer, 0, size, array) attribute.enable() attribute.set_pointer(buffer.ptr) buffers.append(buffer) if size <= 0xff: index_type = GL_UNSIGNED_BYTE index_c_type = ctypes.c_ubyte elif size <= 0xffff: index_type = GL_UNSIGNED_SHORT index_c_type = ctypes.c_ushort else: index_type = GL_UNSIGNED_INT index_c_type = ctypes.c_uint index_array = (index_c_type * len(indices))(*indices) glDrawElements(mode, len(indices), index_type, index_array) glFlush() glPopClientAttrib() def _parse_data(data): '''Given a list of data items, returns (formats, initial_arrays).''' assert data, 'No attribute formats given' # Return tuple (formats, initial_arrays). formats = [] initial_arrays = [] for i, format in enumerate(data): if isinstance(format, tuple): format, array = format initial_arrays.append((i, array)) formats.append(format) formats = tuple(formats) return formats, initial_arrays def _get_default_batch(): shared_object_space = gl.current_context.object_space try: return shared_object_space.pyglet_graphics_default_batch except AttributeError: shared_object_space.pyglet_graphics_default_batch = Batch() return shared_object_space.pyglet_graphics_default_batch def vertex_list(count, *data): '''Create a `VertexList` not associated with a batch, group or mode. :Parameters: `count` : int The number of vertices in the list. `data` : data items Attribute formats and initial data for the vertex list. See the module summary for details. :rtype: `VertexList` ''' # Note that mode=0 because the default batch is never drawn: vertex lists # returned from this function are drawn directly by the app. return _get_default_batch().add(count, 0, None, *data) def vertex_list_indexed(count, indices, *data): '''Create an `IndexedVertexList` not associated with a batch, group or mode. :Parameters: `count` : int The number of vertices in the list. `indices` : sequence Sequence of integers giving indices into the vertex list. `data` : data items Attribute formats and initial data for the vertex list. See the module summary for details. :rtype: `IndexedVertexList` ''' # Note that mode=0 because the default batch is never drawn: vertex lists # returned from this function are drawn directly by the app. return _get_default_batch().add_indexed(count, 0, None, indices, *data) class Batch(object): '''Manage a collection of vertex lists for batched rendering. Vertex lists are added to a `Batch` using the `add` and `add_indexed` methods. An optional group can be specified along with the vertex list, which gives the OpenGL state required for its rendering. Vertex lists with shared mode and group are allocated into adjacent areas of memory and sent to the graphics card in a single operation. Call `VertexList.delete` to remove a vertex list from the batch. ''' def __init__(self): '''Create a graphics batch.''' # Mapping to find domain. # group -> (attributes, mode, indexed) -> domain self.group_map = {} # Mapping of group to list of children. self.group_children = {} # List of top-level groups self.top_groups = [] self._draw_list = [] self._draw_list_dirty = False def invalidate(self): '''Force the batch to update the draw list. This method can be used to force the batch to re-compute the draw list when the ordering of groups has changed. :since: pyglet 1.2 ''' self._draw_list_dirty = True def add(self, count, mode, group, *data): '''Add a vertex list to the batch. :Parameters: `count` : int The number of vertices in the list. `mode` : int OpenGL drawing mode enumeration; for example, one of ``GL_POINTS``, ``GL_LINES``, ``GL_TRIANGLES``, etc. See the module summary for additional information. `group` : `Group` Group of the vertex list, or ``None`` if no group is required. `data` : data items Attribute formats and initial data for the vertex list. See the module summary for details. :rtype: `VertexList` ''' formats, initial_arrays = _parse_data(data) domain = self._get_domain(False, mode, group, formats) # Create vertex list and initialize vlist = domain.create(count) for i, array in initial_arrays: vlist._set_attribute_data(i, array) return vlist def add_indexed(self, count, mode, group, indices, *data): '''Add an indexed vertex list to the batch. :Parameters: `count` : int The number of vertices in the list. `mode` : int OpenGL drawing mode enumeration; for example, one of ``GL_POINTS``, ``GL_LINES``, ``GL_TRIANGLES``, etc. See the module summary for additional information. `group` : `Group` Group of the vertex list, or ``None`` if no group is required. `indices` : sequence Sequence of integers giving indices into the vertex list. `data` : data items Attribute formats and initial data for the vertex list. See the module summary for details. :rtype: `IndexedVertexList` ''' formats, initial_arrays = _parse_data(data) domain = self._get_domain(True, mode, group, formats) # Create vertex list and initialize vlist = domain.create(count, len(indices)) start = vlist.start vlist._set_index_data(map(lambda i: i + start, indices)) for i, array in initial_arrays: vlist._set_attribute_data(i, array) return vlist def migrate(self, vertex_list, mode, group, batch): '''Migrate a vertex list to another batch and/or group. `vertex_list` and `mode` together identify the vertex list to migrate. `group` and `batch` are new owners of the vertex list after migration. The results are undefined if `mode` is not correct or if `vertex_list` does not belong to this batch (they are not checked and will not necessarily throw an exception immediately). `batch` can remain unchanged if only a group change is desired. :Parameters: `vertex_list` : `VertexList` A vertex list currently belonging to this batch. `mode` : int The current GL drawing mode of the vertex list. `group` : `Group` The new group to migrate to. `batch` : `Batch` The batch to migrate to (or the current batch). ''' formats = vertex_list.domain.__formats domain = batch._get_domain(False, mode, group, formats) vertex_list.migrate(domain) def _get_domain(self, indexed, mode, group, formats): if group is None: group = null_group # Batch group if group not in self.group_map: self._add_group(group) domain_map = self.group_map[group] # Find domain given formats, indices and mode key = (formats, mode, indexed) try: domain = domain_map[key] except KeyError: # Create domain if indexed: domain = vertexdomain.create_indexed_domain(*formats) else: domain = vertexdomain.create_domain(*formats) domain.__formats = formats domain_map[key] = domain self._draw_list_dirty = True return domain def _add_group(self, group): self.group_map[group] = {} if group.parent is None: self.top_groups.append(group) else: if group.parent not in self.group_map: self._add_group(group.parent) if group.parent not in self.group_children: self.group_children[group.parent] = [] self.group_children[group.parent].append(group) self._draw_list_dirty = True def _update_draw_list(self): '''Visit group tree in preorder and create a list of bound methods to call. ''' def visit(group): draw_list = [] # Draw domains using this group domain_map = self.group_map[group] for (formats, mode, indexed), domain in list(domain_map.items()): # Remove unused domains from batch if domain._is_empty(): del domain_map[(formats, mode, indexed)] continue draw_list.append( (lambda d, m: lambda: d.draw(m))(domain, mode)) # Sort and visit child groups of this group children = self.group_children.get(group) if children: children.sort() for child in list(children): draw_list.extend(visit(child)) if children or domain_map: return [group.set_state] + draw_list + [group.unset_state] else: # Remove unused group from batch del self.group_map[group] if group.parent: self.group_children[group.parent].remove(group) try: del self.group_children[group] except KeyError: pass try: self.top_groups.remove(group) except ValueError: pass return [] self._draw_list = [] self.top_groups.sort() for group in list(self.top_groups): self._draw_list.extend(visit(group)) self._draw_list_dirty = False if _debug_graphics_batch: self._dump_draw_list() def _dump_draw_list(self): def dump(group, indent=''): print indent, 'Begin group', group domain_map = self.group_map[group] for _, domain in domain_map.items(): print indent, ' ', domain for start, size in zip(*domain.allocator.get_allocated_regions()): print indent, ' ', 'Region %d size %d:' % (start, size) for key, attribute in domain.attribute_names.items(): print indent, ' ', try: region = attribute.get_region(attribute.buffer, start, size) print key, region.array[:] except: print key, '(unmappable)' for child in self.group_children.get(group, ()): dump(child, indent + ' ') print indent, 'End group', group print 'Draw list for %r:' % self for group in self.top_groups: dump(group) def draw(self): '''Draw the batch. ''' if self._draw_list_dirty: self._update_draw_list() for func in self._draw_list: func() def draw_subset(self, vertex_lists): '''Draw only some vertex lists in the batch. The use of this method is highly discouraged, as it is quite inefficient. Usually an application can be redesigned so that batches can always be drawn in their entirety, using `draw`. The given vertex lists must belong to this batch; behaviour is undefined if this condition is not met. :Parameters: `vertex_lists` : sequence of `VertexList` or `IndexedVertexList` Vertex lists to draw. ''' # Horrendously inefficient. def visit(group): group.set_state() # Draw domains using this group domain_map = self.group_map[group] for (_, mode, _), domain in domain_map.items(): for alist in vertex_lists: if alist.domain is domain: alist.draw(mode) # Sort and visit child groups of this group children = self.group_children.get(group) if children: children.sort() for child in children: visit(child) group.unset_state() self.top_groups.sort() for group in self.top_groups: visit(group) class Group(object): '''Group of common OpenGL state. Before a vertex list is rendered, its group's OpenGL state is set; as are that state's ancestors' states. This can be defined arbitrarily on subclasses; the default state change has no effect, and groups vertex lists only in the order in which they are drawn. ''' def __init__(self, parent=None): '''Create a group. :Parameters: `parent` : `Group` Group to contain this group; its state will be set before this state's. ''' self.parent = parent def __lt__(self, other): return hash(self) < hash(other) def set_state(self): '''Apply the OpenGL state change. The default implementation does nothing.''' pass def unset_state(self): '''Repeal the OpenGL state change. The default implementation does nothing.''' pass def set_state_recursive(self): '''Set this group and its ancestry. Call this method if you are using a group in isolation: the parent groups will be called in top-down order, with this class's `set` being called last. ''' if self.parent: self.parent.set_state_recursive() self.set_state() def unset_state_recursive(self): '''Unset this group and its ancestry. The inverse of `set_state_recursive`. ''' self.unset_state() if self.parent: self.parent.unset_state_recursive() class NullGroup(Group): '''The default group class used when ``None`` is given to a batch. This implementation has no effect. ''' pass #: The default group. #: #: :type: `Group` null_group = NullGroup() class TextureGroup(Group): '''A group that enables and binds a texture. Texture groups are equal if their textures' targets and names are equal. ''' # Don't use this, create your own group classes that are more specific. # This is just an example. def __init__(self, texture, parent=None): '''Create a texture group. :Parameters: `texture` : `Texture` Texture to bind. `parent` : `Group` Parent group. ''' super(TextureGroup, self).__init__(parent) self.texture = texture def set_state(self): glEnable(self.texture.target) glBindTexture(self.texture.target, self.texture.id) def unset_state(self): glDisable(self.texture.target) def __hash__(self): return hash((self.texture.target, self.texture.id, self.parent)) def __eq__(self, other): return (self.__class__ is other.__class__ and self.texture.target == other.texture.target and self.texture.id == other.texture.id and self.parent == other.parent) def __repr__(self): return '%s(id=%d)' % (self.__class__.__name__, self.texture.id) class OrderedGroup(Group): '''A group with partial order. Ordered groups with a common parent are rendered in ascending order of their ``order`` field. This is a useful way to render multiple layers of a scene within a single batch. ''' # This can be useful as a top-level group, or as a superclass for other # groups that need to be ordered. # # As a top-level group it's useful because graphics can be composited in a # known order even if they don't know about each other or share any known # group. def __init__(self, order, parent=None): '''Create an ordered group. :Parameters: `order` : int Order of this group. `parent` : `Group` Parent of this group. ''' super(OrderedGroup, self).__init__(parent) self.order = order def __lt__(self, other): if isinstance(other, OrderedGroup): return self.order < other.order return super(OrderedGroup, self).__lt__(other) def __eq__(self, other): return (self.__class__ is other.__class__ and self.order == other.order and self.parent == other.parent) def __hash__(self): return hash((self.order, self.parent)) def __repr__(self): return '%s(%d)' % (self.__class__.__name__, self.order)
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id:$ '''Manage related vertex attributes within a single vertex domain. A vertex "domain" consists of a set of attribute descriptions that together describe the layout of one or more vertex buffers which are used together to specify the vertices in a primitive. Additionally, the domain manages the buffers used to store the data and will resize them as necessary to accommodate new vertices. Domains can optionally be indexed, in which case they also manage a buffer containing vertex indices. This buffer is grown separately and has no size relation to the attribute buffers. Applications can create vertices (and optionally, indices) within a domain with the `VertexDomain.create` method. This returns a `VertexList` representing the list of vertices created. The vertex attribute data within the group can be modified, and the changes will be made to the underlying buffers automatically. The entire domain can be efficiently drawn in one step with the `VertexDomain.draw` method, assuming all the vertices comprise primitives of the same OpenGL primitive mode. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes import re from pyglet.gl import * from pyglet.graphics import allocation, vertexattribute, vertexbuffer _usage_format_re = re.compile(r''' (?P<attribute>[^/]*) (/ (?P<usage> static|dynamic|stream|none))? ''', re.VERBOSE) _gl_usages = { 'static': GL_STATIC_DRAW, 'dynamic': GL_DYNAMIC_DRAW, 'stream': GL_STREAM_DRAW, 'none': GL_STREAM_DRAW_ARB, # Force no VBO } def _nearest_pow2(v): # From http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 # Credit: Sean Anderson v -= 1 v |= v >> 1 v |= v >> 2 v |= v >> 4 v |= v >> 8 v |= v >> 16 return v + 1 def create_attribute_usage(format): '''Create an attribute and usage pair from a format string. The format string is as documented in `pyglet.graphics.vertexattribute`, with the addition of an optional usage component:: usage ::= attribute ( '/' ('static' | 'dynamic' | 'stream' | 'none') )? If the usage is not given it defaults to 'dynamic'. The usage corresponds to the OpenGL VBO usage hint, and for ``static`` also indicates a preference for interleaved arrays. If ``none`` is specified a buffer object is not created, and vertex data is stored in system memory. Some examples: ``v3f/stream`` 3D vertex position using floats, for stream usage ``c4b/static`` 4-byte color attribute, for static usage :return: attribute, usage ''' match = _usage_format_re.match(format) attribute_format = match.group('attribute') attribute = vertexattribute.create_attribute(attribute_format) usage = match.group('usage') if usage: vbo = not usage == 'none' usage = _gl_usages[usage] else: usage = GL_DYNAMIC_DRAW vbo = True return (attribute, usage, vbo) def create_domain(*attribute_usage_formats): '''Create a vertex domain covering the given attribute usage formats. See documentation for `create_attribute_usage` and `pyglet.graphics.vertexattribute.create_attribute` for the grammar of these format strings. :rtype: `VertexDomain` ''' attribute_usages = [create_attribute_usage(f) \ for f in attribute_usage_formats] return VertexDomain(attribute_usages) def create_indexed_domain(*attribute_usage_formats): '''Create an indexed vertex domain covering the given attribute usage formats. See documentation for `create_attribute_usage` and `pyglet.graphics.vertexattribute.create_attribute` for the grammar of these format strings. :rtype: `VertexDomain` ''' attribute_usages = [create_attribute_usage(f) \ for f in attribute_usage_formats] return IndexedVertexDomain(attribute_usages) class VertexDomain(object): '''Management of a set of vertex lists. Construction of a vertex domain is usually done with the `create_domain` function. ''' _version = 0 _initial_count = 16 def __init__(self, attribute_usages): self.allocator = allocation.Allocator(self._initial_count) # If there are any MultiTexCoord attributes, then a TexCoord attribute # must be converted. have_multi_texcoord = False for attribute, _, _ in attribute_usages: if isinstance(attribute, vertexattribute.MultiTexCoordAttribute): have_multi_texcoord = True break static_attributes = [] attributes = [] self.buffer_attributes = [] # list of (buffer, attributes) for attribute, usage, vbo in attribute_usages: if (have_multi_texcoord and isinstance(attribute, vertexattribute.TexCoordAttribute)): attribute.convert_to_multi_tex_coord_attribute() if usage == GL_STATIC_DRAW: # Group attributes for interleaved buffer static_attributes.append(attribute) attributes.append(attribute) else: # Create non-interleaved buffer attributes.append(attribute) attribute.buffer = vertexbuffer.create_mappable_buffer( attribute.stride * self.allocator.capacity, usage=usage, vbo=vbo) attribute.buffer.element_size = attribute.stride attribute.buffer.attributes = (attribute,) self.buffer_attributes.append( (attribute.buffer, (attribute,))) # Create buffer for interleaved data if static_attributes: vertexattribute.interleave_attributes(static_attributes) stride = static_attributes[0].stride buffer = vertexbuffer.create_mappable_buffer( stride * self.allocator.capacity, usage=GL_STATIC_DRAW) buffer.element_size = stride self.buffer_attributes.append( (buffer, static_attributes)) attributes.extend(static_attributes) for attribute in static_attributes: attribute.buffer = buffer # Create named attributes for each attribute self.attributes = attributes self.attribute_names = {} for attribute in attributes: if isinstance(attribute, vertexattribute.GenericAttribute): index = attribute.index # TODO create a name and use it (e.g. 'generic3') # XXX this won't migrate; not documented. if 'generic' not in self.attribute_names: self.attribute_names['generic'] = {} assert index not in self.attribute_names['generic'], \ 'More than one generic attribute with index %d' % index self.attribute_names['generic'][index] = attribute elif isinstance(attribute, vertexattribute.MultiTexCoordAttribute): # XXX this won't migrate; not documented. texture = attribute.texture if 'multi_tex_coords' not in self.attribute_names: self.attribute_names['multi_tex_coords'] = {} assert texture not in self.attribute_names['multi_tex_coords'],\ 'More than one multi_tex_coord attribute for texture %d' % \ texture self.attribute_names['multi_tex_coords'][texture] = attribute else: name = attribute.plural assert name not in self.attributes, \ 'More than one "%s" attribute given' % name self.attribute_names[name] = attribute def __del__(self): # Break circular refs that Python GC seems to miss even when forced # collection. for attribute in self.attributes: try: del attribute.buffer except AttributeError: pass def _safe_alloc(self, count): '''Allocate vertices, resizing the buffers if necessary.''' try: return self.allocator.alloc(count) except allocation.AllocatorMemoryException, e: capacity = _nearest_pow2(e.requested_capacity) self._version += 1 for buffer, _ in self.buffer_attributes: buffer.resize(capacity * buffer.element_size) self.allocator.set_capacity(capacity) return self.allocator.alloc(count) def _safe_realloc(self, start, count, new_count): '''Reallocate vertices, resizing the buffers if necessary.''' try: return self.allocator.realloc(start, count, new_count) except allocation.AllocatorMemoryException, e: capacity = _nearest_pow2(e.requested_capacity) self._version += 1 for buffer, _ in self.buffer_attributes: buffer.resize(capacity * buffer.element_size) self.allocator.set_capacity(capacity) return self.allocator.realloc(start, count, new_count) def create(self, count): '''Create a `VertexList` in this domain. :Parameters: `count` : int Number of vertices to create. :rtype: `VertexList` ''' start = self._safe_alloc(count) return VertexList(self, start, count) def draw(self, mode, vertex_list=None): '''Draw vertices in the domain. If `vertex_list` is not specified, all vertices in the domain are drawn. This is the most efficient way to render primitives. If `vertex_list` specifies a `VertexList`, only primitives in that list will be drawn. :Parameters: `mode` : int OpenGL drawing mode, e.g. ``GL_POINTS``, ``GL_LINES``, etc. `vertex_list` : `VertexList` Vertex list to draw, or ``None`` for all lists in this domain. ''' glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) for buffer, attributes in self.buffer_attributes: buffer.bind() for attribute in attributes: attribute.enable() attribute.set_pointer(attribute.buffer.ptr) if vertexbuffer._workaround_vbo_finish: glFinish() if vertex_list is not None: glDrawArrays(mode, vertex_list.start, vertex_list.count) else: starts, sizes = self.allocator.get_allocated_regions() primcount = len(starts) if primcount == 0: pass elif primcount == 1: # Common case glDrawArrays(mode, starts[0], sizes[0]) elif gl_info.have_version(1, 4): starts = (GLint * primcount)(*starts) sizes = (GLsizei * primcount)(*sizes) glMultiDrawArrays(mode, starts, sizes, primcount) else: for start, size in zip(starts, sizes): glDrawArrays(mode, start, size) for buffer, _ in self.buffer_attributes: buffer.unbind() glPopClientAttrib() def _is_empty(self): return not self.allocator.starts def __repr__(self): return '<%s@%x %s>' % (self.__class__.__name__, id(self), self.allocator) class VertexList(object): '''A list of vertices within a `VertexDomain`. Use `VertexDomain.create` to construct this list. ''' def __init__(self, domain, start, count): # TODO make private self.domain = domain self.start = start self.count = count def get_size(self): '''Get the number of vertices in the list. :rtype: int ''' return self.count def get_domain(self): '''Get the domain this vertex list belongs to. :rtype: `VertexDomain` ''' return self.domain def draw(self, mode): '''Draw this vertex list in the given OpenGL mode. :Parameters: `mode` : int OpenGL drawing mode, e.g. ``GL_POINTS``, ``GL_LINES``, etc. ''' self.domain.draw(mode, self) def resize(self, count): '''Resize this group. :Parameters: `count` : int New number of vertices in the list. ''' new_start = self.domain._safe_realloc(self.start, self.count, count) if new_start != self.start: # Copy contents to new location for attribute in self.domain.attributes: old = attribute.get_region(attribute.buffer, self.start, self.count) new = attribute.get_region(attribute.buffer, new_start, self.count) new.array[:] = old.array[:] new.invalidate() self.start = new_start self.count = count self._colors_cache_version = None self._fog_coords_cache_version = None self._edge_flags_cache_version = None self._normals_cache_version = None self._secondary_colors_cache_version = None self._tex_coords_cache_version = None self._vertices_cache_version = None def delete(self): '''Delete this group.''' self.domain.allocator.dealloc(self.start, self.count) def migrate(self, domain): '''Move this group from its current domain and add to the specified one. Attributes on domains must match. (In practice, used to change parent state of some vertices). :Parameters: `domain` : `VertexDomain` Domain to migrate this vertex list to. ''' assert domain.attribute_names.keys() == \ self.domain.attribute_names.keys(), 'Domain attributes must match.' new_start = domain._safe_alloc(self.count) for key, old_attribute in self.domain.attribute_names.items(): old = old_attribute.get_region(old_attribute.buffer, self.start, self.count) new_attribute = domain.attribute_names[key] new = new_attribute.get_region(new_attribute.buffer, new_start, self.count) new.array[:] = old.array[:] new.invalidate() self.domain.allocator.dealloc(self.start, self.count) self.domain = domain self.start = new_start self._colors_cache_version = None self._fog_coords_cache_version = None self._edge_flags_cache_version = None self._normals_cache_version = None self._secondary_colors_cache_version = None self._tex_coords_cache_version = None self._vertices_cache_version = None def _set_attribute_data(self, i, data): attribute = self.domain.attributes[i] # TODO without region region = attribute.get_region(attribute.buffer, self.start, self.count) region.array[:] = data region.invalidate() # --- def _get_colors(self): if (self._colors_cache_version != self.domain._version): domain = self.domain attribute = domain.attribute_names['colors'] self._colors_cache = attribute.get_region( attribute.buffer, self.start, self.count) self._colors_cache_version = domain._version region = self._colors_cache region.invalidate() return region.array def _set_colors(self, data): self._get_colors()[:] = data _colors_cache = None _colors_cache_version = None colors = property(_get_colors, _set_colors, doc='''Array of color data.''') # --- def _get_fog_coords(self): if (self._fog_coords_cache_version != self.domain._version): domain = self.domain attribute = domain.attribute_names['fog_coords'] self._fog_coords_cache = attribute.get_region( attribute.buffer, self.start, self.count) self._fog_coords_cache_version = domain._version region = self._fog_coords_cache region.invalidate() return region.array def _set_fog_coords(self, data): self._get_fog_coords()[:] = data _fog_coords_cache = None _fog_coords_cache_version = None fog_coords = property(_get_fog_coords, _set_fog_coords, doc='''Array of fog coordinate data.''') # --- def _get_edge_flags(self): if (self._edge_flags_cache_version != self.domain._version): domain = self.domain attribute = domain.attribute_names['edge_flags'] self._edge_flags_cache = attribute.get_region( attribute.buffer, self.start, self.count) self._edge_flags_cache_version = domain._version region = self._edge_flags_cache region.invalidate() return region.array def _set_edge_flags(self, data): self._get_edge_flags()[:] = data _edge_flags_cache = None _edge_flags_cache_version = None edge_flags = property(_get_edge_flags, _set_edge_flags, doc='''Array of edge flag data.''') # --- def _get_normals(self): if (self._normals_cache_version != self.domain._version): domain = self.domain attribute = domain.attribute_names['normals'] self._normals_cache = attribute.get_region( attribute.buffer, self.start, self.count) self._normals_cache_version = domain._version region = self._normals_cache region.invalidate() return region.array def _set_normals(self, data): self._get_normals()[:] = data _normals_cache = None _normals_cache_version = None normals = property(_get_normals, _set_normals, doc='''Array of normal vector data.''') # --- def _get_secondary_colors(self): if (self._secondary_colors_cache_version != self.domain._version): domain = self.domain attribute = domain.attribute_names['secondary_colors'] self._secondary_colors_cache = attribute.get_region( attribute.buffer, self.start, self.count) self._secondary_colors_cache_version = domain._version region = self._secondary_colors_cache region.invalidate() return region.array def _set_secondary_colors(self, data): self._get_secondary_colors()[:] = data _secondary_colors_cache = None _secondary_colors_cache_version = None secondary_colors = property(_get_secondary_colors, _set_secondary_colors, doc='''Array of secondary color data.''') # --- _tex_coords_cache = None _tex_coords_cache_version = None def _get_tex_coords(self): if (self._tex_coords_cache_version != self.domain._version): domain = self.domain attribute = domain.attribute_names['tex_coords'] self._tex_coords_cache = attribute.get_region( attribute.buffer, self.start, self.count) self._tex_coords_cache_version = domain._version region = self._tex_coords_cache region.invalidate() return region.array def _set_tex_coords(self, data): self._get_tex_coords()[:] = data tex_coords = property(_get_tex_coords, _set_tex_coords, doc='''Array of texture coordinate data.''') # --- _vertices_cache = None _vertices_cache_version = None def _get_vertices(self): if (self._vertices_cache_version != self.domain._version): domain = self.domain attribute = domain.attribute_names['vertices'] self._vertices_cache = attribute.get_region( attribute.buffer, self.start, self.count) self._vertices_cache_version = domain._version region = self._vertices_cache region.invalidate() return region.array def _set_vertices(self, data): self._get_vertices()[:] = data vertices = property(_get_vertices, _set_vertices, doc='''Array of vertex coordinate data.''') class IndexedVertexDomain(VertexDomain): '''Management of a set of indexed vertex lists. Construction of an indexed vertex domain is usually done with the `create_indexed_domain` function. ''' _initial_index_count = 16 def __init__(self, attribute_usages, index_gl_type=GL_UNSIGNED_INT): super(IndexedVertexDomain, self).__init__(attribute_usages) self.index_allocator = allocation.Allocator(self._initial_index_count) self.index_gl_type = index_gl_type self.index_c_type = vertexattribute._c_types[index_gl_type] self.index_element_size = ctypes.sizeof(self.index_c_type) self.index_buffer = vertexbuffer.create_mappable_buffer( self.index_allocator.capacity * self.index_element_size, target=GL_ELEMENT_ARRAY_BUFFER) def _safe_index_alloc(self, count): '''Allocate indices, resizing the buffers if necessary.''' try: return self.index_allocator.alloc(count) except allocation.AllocatorMemoryException, e: capacity = _nearest_pow2(e.requested_capacity) self._version += 1 self.index_buffer.resize(capacity * self.index_element_size) self.index_allocator.set_capacity(capacity) return self.index_allocator.alloc(count) def _safe_index_realloc(self, start, count, new_count): '''Reallocate indices, resizing the buffers if necessary.''' try: return self.index_allocator.realloc(start, count, new_count) except allocation.AllocatorMemoryException, e: capacity = _nearest_pow2(e.requested_capacity) self._version += 1 self.index_buffer.resize(capacity * self.index_element_size) self.index_allocator.set_capacity(capacity) return self.index_allocator.realloc(start, count, new_count) def create(self, count, index_count): '''Create an `IndexedVertexList` in this domain. :Parameters: `count` : int Number of vertices to create `index_count` Number of indices to create ''' start = self._safe_alloc(count) index_start = self._safe_index_alloc(index_count) return IndexedVertexList(self, start, count, index_start, index_count) def get_index_region(self, start, count): '''Get a region of the index buffer. :Parameters: `start` : int Start of the region to map. `count` : int Number of indices to map. :rtype: Array of int ''' byte_start = self.index_element_size * start byte_count = self.index_element_size * count ptr_type = ctypes.POINTER(self.index_c_type * count) return self.index_buffer.get_region(byte_start, byte_count, ptr_type) def draw(self, mode, vertex_list=None): '''Draw vertices in the domain. If `vertex_list` is not specified, all vertices in the domain are drawn. This is the most efficient way to render primitives. If `vertex_list` specifies a `VertexList`, only primitives in that list will be drawn. :Parameters: `mode` : int OpenGL drawing mode, e.g. ``GL_POINTS``, ``GL_LINES``, etc. `vertex_list` : `IndexedVertexList` Vertex list to draw, or ``None`` for all lists in this domain. ''' glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) for buffer, attributes in self.buffer_attributes: buffer.bind() for attribute in attributes: attribute.enable() attribute.set_pointer(attribute.buffer.ptr) self.index_buffer.bind() if vertexbuffer._workaround_vbo_finish: glFinish() if vertex_list is not None: glDrawElements(mode, vertex_list.index_count, self.index_gl_type, self.index_buffer.ptr + vertex_list.index_start * self.index_element_size) else: starts, sizes = self.index_allocator.get_allocated_regions() primcount = len(starts) if primcount == 0: pass elif primcount == 1: # Common case glDrawElements(mode, sizes[0], self.index_gl_type, self.index_buffer.ptr + starts[0]) elif gl_info.have_version(1, 4): starts = [s * self.index_element_size + self.index_buffer.ptr for s in starts] starts = ctypes.cast((GLuint * primcount)(*starts), ctypes.POINTER(ctypes.c_void_p)) sizes = (GLsizei * primcount)(*sizes) glMultiDrawElements(mode, sizes, GL_UNSIGNED_INT, starts, primcount) else: for start, size in zip(starts, sizes): glDrawElements(mode, size, self.index_gl_type, self.index_buffer.ptr + start * self.index_element_size) self.index_buffer.unbind() for buffer, _ in self.buffer_attributes: buffer.unbind() glPopClientAttrib() class IndexedVertexList(VertexList): '''A list of vertices within an `IndexedVertexDomain` that are indexed. Use `IndexedVertexDomain.create` to construct this list. ''' def __init__(self, domain, start, count, index_start, index_count): super(IndexedVertexList, self).__init__(domain, start, count) self.index_start = index_start self.index_count = index_count def draw(self, mode): self.domain.draw(mode, self) def resize(self, count, index_count): '''Resize this group. :Parameters: `count` : int New number of vertices in the list. `index_count` : int New number of indices in the list. ''' old_start = self.start super(IndexedVertexList, self).resize(count) # Change indices (because vertices moved) if old_start != self.start: diff = self.start - old_start self.indices[:] = map(lambda i: i + diff, self.indices) # Resize indices new_start = self.domain._safe_index_realloc( self.index_start, self.index_count, index_count) if new_start != self.index_start: old = self.domain.get_index_region( self.index_start, self.index_count) new = self.domain.get_index_region( self.index_start, self.index_count) new.array[:] = old.array[:] new.invalidate() self.index_start = new_start self.index_count = index_count self._indices_cache_version = None def delete(self): '''Delete this group.''' super(IndexedVertexList, self).delete() self.domain.index_allocator.dealloc(self.index_start, self.index_count) def _set_index_data(self, data): # TODO without region region = self.domain.get_index_region( self.index_start, self.index_count) region.array[:] = data region.invalidate() # --- def _get_indices(self): if self._indices_cache_version != self.domain._version: domain = self.domain self._indices_cache = domain.get_index_region( self.index_start, self.index_count) self._indices_cache_version = domain._version region = self._indices_cache region.invalidate() return region.array def _set_indices(self, data): self._get_indices()[:] = data _indices_cache = None _indices_cache_version = None indices = property(_get_indices, _set_indices, doc='''Array of index data.''')
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Simple Python-only RIFF reader, supports uncompressed WAV files. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' # RIFF reference: # http://www.saettler.com/RIFFMCI/riffmci.html # # More readable WAVE summaries: # # http://www.borg.com/~jglatt/tech/wave.htm # http://www.sonicspot.com/guide/wavefiles.html from pyglet.media import StreamingSource, AudioData, AudioFormat from pyglet.media import MediaFormatException from pyglet.compat import BytesIO, asbytes import struct WAVE_FORMAT_PCM = 0x0001 IBM_FORMAT_MULAW = 0x0101 IBM_FORMAT_ALAW = 0x0102 IBM_FORMAT_ADPCM = 0x0103 class RIFFFormatException(MediaFormatException): pass class WAVEFormatException(RIFFFormatException): pass class RIFFChunk(object): header_fmt = '<4sL' header_length = struct.calcsize(header_fmt) def __init__(self, file, name, length, offset): self.file = file self.name = name self.length = length self.offset = offset def get_data(self): self.file.seek(self.offset) return self.file.read(self.length) def __repr__(self): return '%s(%r, offset=%r, length=%r)' % ( self.__class__.__name__, self.name, self.offset, self.length) class RIFFForm(object): _chunks = None def __init__(self, file, offset): self.file = file self.offset = offset def get_chunks(self): if self._chunks: return self._chunks self._chunks = [] self.file.seek(self.offset) offset = self.offset while True: header = self.file.read(RIFFChunk.header_length) if not header: break name, length = struct.unpack(RIFFChunk.header_fmt, header) offset += RIFFChunk.header_length cls = self._chunk_types.get(name, RIFFChunk) chunk = cls(self.file, name, length, offset) self._chunks.append(chunk) offset += length if offset & 0x3 != 0: offset = (offset | 0x3) + 1 self.file.seek(offset) return self._chunks def __repr__(self): return '%s(offset=%r)' % (self.__class__.__name__, self.offset) class RIFFType(RIFFChunk): def __init__(self, *args, **kwargs): super(RIFFType, self).__init__(*args, **kwargs) self.file.seek(self.offset) form = self.file.read(4) if form != asbytes('WAVE'): raise RIFFFormatException('Unsupported RIFF form "%s"' % form) self.form = WaveForm(self.file, self.offset + 4) class RIFFFile(RIFFForm): _chunk_types = { asbytes('RIFF'): RIFFType, } def __init__(self, file): if not hasattr(file, 'seek'): file = BytesIO(file.read()) super(RIFFFile, self).__init__(file, 0) def get_wave_form(self): chunks = self.get_chunks() if len(chunks) == 1 and isinstance(chunks[0], RIFFType): return chunks[0].form class WaveFormatChunk(RIFFChunk): def __init__(self, *args, **kwargs): super(WaveFormatChunk, self).__init__(*args, **kwargs) fmt = '<HHLLHH' if struct.calcsize(fmt) != self.length: raise RIFFFormatException('Size of format chunk is incorrect.') (self.wFormatTag, self.wChannels, self.dwSamplesPerSec, self.dwAvgBytesPerSec, self.wBlockAlign, self.wBitsPerSample) = struct.unpack(fmt, self.get_data()) class WaveDataChunk(RIFFChunk): pass class WaveForm(RIFFForm): _chunk_types = { asbytes('fmt '): WaveFormatChunk, asbytes('data'): WaveDataChunk } def get_format_chunk(self): for chunk in self.get_chunks(): if isinstance(chunk, WaveFormatChunk): return chunk def get_data_chunk(self): for chunk in self.get_chunks(): if isinstance(chunk, WaveDataChunk): return chunk class WaveSource(StreamingSource): def __init__(self, filename, file=None): if file is None: file = open(filename, 'rb') self._file = file # Read RIFF format, get format and data chunks riff = RIFFFile(file) wave_form = riff.get_wave_form() if wave_form: format = wave_form.get_format_chunk() data_chunk = wave_form.get_data_chunk() if not wave_form or not format or not data_chunk: if not filename or filename.lower().endswith('.wav'): raise WAVEFormatException('Not a WAVE file') else: raise WAVEFormatException( 'AVbin is required to decode compressed media') if format.wFormatTag != WAVE_FORMAT_PCM: raise WAVEFormatException('Unsupported WAVE format category') if format.wBitsPerSample not in (8, 16): raise WAVEFormatException('Unsupported sample bit size: %d' % format.wBitsPerSample) self.audio_format = AudioFormat( channels=format.wChannels, sample_size=format.wBitsPerSample, sample_rate=format.dwSamplesPerSec) self._duration = \ float(data_chunk.length) / self.audio_format.bytes_per_second self._start_offset = data_chunk.offset self._max_offset = data_chunk.length self._offset = 0 self._file.seek(self._start_offset) def get_audio_data(self, bytes): bytes = min(bytes, self._max_offset - self._offset) if not bytes: return None data = self._file.read(bytes) self._offset += len(data) timestamp = float(self._offset) / self.audio_format.bytes_per_second duration = float(bytes) / self.audio_format.bytes_per_second return AudioData(data, len(data), timestamp, duration, []) def seek(self, timestamp): offset = int(timestamp * self.audio_format.bytes_per_second) # Bound within duration offset = min(max(offset, 0), self._max_offset) # Align to sample if self.audio_format.bytes_per_sample == 2: offset &= 0xfffffffe elif self.audio_format.bytes_per_sample == 4: offset &= 0xfffffffc self._file.seek(offset + self._start_offset) self._offset = offset
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Wrapper for openal Generated with: ../tools/wraptypes/wrap.py /usr/include/AL/al.h -lopenal -olib_openal.py .. Hacked to remove non-existent library functions. TODO add alGetError check. .. alListener3i and alListeneriv are present in my OS X 10.4 but not another 10.4 user's installation. They've also been removed for compatibility. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import ctypes from ctypes import * import sys import pyglet.lib _lib = pyglet.lib.load_library('openal', win32='openal32', framework='/System/Library/Frameworks/OpenAL.framework') _int_types = (c_int16, c_int32) if hasattr(ctypes, 'c_int64'): # Some builds of ctypes apparently do not have c_int64 # defined; it's a pretty good bet that these builds do not # have 64-bit pointers. _int_types += (ctypes.c_int64,) for t in _int_types: if sizeof(t) == sizeof(c_size_t): c_ptrdiff_t = t class c_void(Structure): # c_void_p is a buggy return type, converting to int, so # POINTER(None) == c_void_p is actually written as # POINTER(c_void), so it can be treated as a real pointer. _fields_ = [('dummy', c_int)] AL_API = 0 # /usr/include/AL/al.h:39 ALAPI = 0 # /usr/include/AL/al.h:59 AL_INVALID = -1 # /usr/include/AL/al.h:61 AL_ILLEGAL_ENUM = 0 # /usr/include/AL/al.h:62 AL_ILLEGAL_COMMAND = 0 # /usr/include/AL/al.h:63 ALboolean = c_int # Better return type than c_char, as generated ALchar = c_char # /usr/include/AL/al.h:73 ALbyte = c_char # /usr/include/AL/al.h:76 ALubyte = c_ubyte # /usr/include/AL/al.h:79 ALshort = c_short # /usr/include/AL/al.h:82 ALushort = c_ushort # /usr/include/AL/al.h:85 ALint = c_int # /usr/include/AL/al.h:88 ALuint = c_uint # /usr/include/AL/al.h:91 ALsizei = c_int # /usr/include/AL/al.h:94 ALenum = c_int # /usr/include/AL/al.h:97 ALfloat = c_float # /usr/include/AL/al.h:100 ALdouble = c_double # /usr/include/AL/al.h:103 ALvoid = None # /usr/include/AL/al.h:106 AL_NONE = 0 # /usr/include/AL/al.h:112 AL_FALSE = 0 # /usr/include/AL/al.h:115 AL_TRUE = 1 # /usr/include/AL/al.h:118 AL_SOURCE_RELATIVE = 514 # /usr/include/AL/al.h:121 AL_CONE_INNER_ANGLE = 4097 # /usr/include/AL/al.h:130 AL_CONE_OUTER_ANGLE = 4098 # /usr/include/AL/al.h:137 AL_PITCH = 4099 # /usr/include/AL/al.h:145 AL_POSITION = 4100 # /usr/include/AL/al.h:157 AL_DIRECTION = 4101 # /usr/include/AL/al.h:160 AL_VELOCITY = 4102 # /usr/include/AL/al.h:163 AL_LOOPING = 4103 # /usr/include/AL/al.h:171 AL_BUFFER = 4105 # /usr/include/AL/al.h:178 AL_GAIN = 4106 # /usr/include/AL/al.h:191 AL_MIN_GAIN = 4109 # /usr/include/AL/al.h:200 AL_MAX_GAIN = 4110 # /usr/include/AL/al.h:209 AL_ORIENTATION = 4111 # /usr/include/AL/al.h:216 AL_SOURCE_STATE = 4112 # /usr/include/AL/al.h:221 AL_INITIAL = 4113 # /usr/include/AL/al.h:222 AL_PLAYING = 4114 # /usr/include/AL/al.h:223 AL_PAUSED = 4115 # /usr/include/AL/al.h:224 AL_STOPPED = 4116 # /usr/include/AL/al.h:225 AL_BUFFERS_QUEUED = 4117 # /usr/include/AL/al.h:230 AL_BUFFERS_PROCESSED = 4118 # /usr/include/AL/al.h:231 AL_SEC_OFFSET = 4132 # /usr/include/AL/al.h:236 AL_SAMPLE_OFFSET = 4133 # /usr/include/AL/al.h:237 AL_BYTE_OFFSET = 4134 # /usr/include/AL/al.h:238 AL_SOURCE_TYPE = 4135 # /usr/include/AL/al.h:246 AL_STATIC = 4136 # /usr/include/AL/al.h:247 AL_STREAMING = 4137 # /usr/include/AL/al.h:248 AL_UNDETERMINED = 4144 # /usr/include/AL/al.h:249 AL_FORMAT_MONO8 = 4352 # /usr/include/AL/al.h:252 AL_FORMAT_MONO16 = 4353 # /usr/include/AL/al.h:253 AL_FORMAT_STEREO8 = 4354 # /usr/include/AL/al.h:254 AL_FORMAT_STEREO16 = 4355 # /usr/include/AL/al.h:255 AL_REFERENCE_DISTANCE = 4128 # /usr/include/AL/al.h:265 AL_ROLLOFF_FACTOR = 4129 # /usr/include/AL/al.h:273 AL_CONE_OUTER_GAIN = 4130 # /usr/include/AL/al.h:282 AL_MAX_DISTANCE = 4131 # /usr/include/AL/al.h:292 AL_FREQUENCY = 8193 # /usr/include/AL/al.h:300 AL_BITS = 8194 # /usr/include/AL/al.h:301 AL_CHANNELS = 8195 # /usr/include/AL/al.h:302 AL_SIZE = 8196 # /usr/include/AL/al.h:303 AL_UNUSED = 8208 # /usr/include/AL/al.h:310 AL_PENDING = 8209 # /usr/include/AL/al.h:311 AL_PROCESSED = 8210 # /usr/include/AL/al.h:312 AL_NO_ERROR = 0 # /usr/include/AL/al.h:316 AL_INVALID_NAME = 40961 # /usr/include/AL/al.h:321 AL_INVALID_ENUM = 40962 # /usr/include/AL/al.h:326 AL_INVALID_VALUE = 40963 # /usr/include/AL/al.h:331 AL_INVALID_OPERATION = 40964 # /usr/include/AL/al.h:336 AL_OUT_OF_MEMORY = 40965 # /usr/include/AL/al.h:342 AL_VENDOR = 45057 # /usr/include/AL/al.h:346 AL_VERSION = 45058 # /usr/include/AL/al.h:347 AL_RENDERER = 45059 # /usr/include/AL/al.h:348 AL_EXTENSIONS = 45060 # /usr/include/AL/al.h:349 AL_DOPPLER_FACTOR = 49152 # /usr/include/AL/al.h:356 AL_DOPPLER_VELOCITY = 49153 # /usr/include/AL/al.h:361 AL_SPEED_OF_SOUND = 49155 # /usr/include/AL/al.h:366 AL_DISTANCE_MODEL = 53248 # /usr/include/AL/al.h:375 AL_INVERSE_DISTANCE = 53249 # /usr/include/AL/al.h:376 AL_INVERSE_DISTANCE_CLAMPED = 53250 # /usr/include/AL/al.h:377 AL_LINEAR_DISTANCE = 53251 # /usr/include/AL/al.h:378 AL_LINEAR_DISTANCE_CLAMPED = 53252 # /usr/include/AL/al.h:379 AL_EXPONENT_DISTANCE = 53253 # /usr/include/AL/al.h:380 AL_EXPONENT_DISTANCE_CLAMPED = 53254 # /usr/include/AL/al.h:381 # /usr/include/AL/al.h:386 alEnable = _lib.alEnable alEnable.restype = None alEnable.argtypes = [ALenum] # /usr/include/AL/al.h:388 alDisable = _lib.alDisable alDisable.restype = None alDisable.argtypes = [ALenum] # /usr/include/AL/al.h:390 alIsEnabled = _lib.alIsEnabled alIsEnabled.restype = ALboolean alIsEnabled.argtypes = [ALenum] # /usr/include/AL/al.h:396 alGetString = _lib.alGetString alGetString.restype = POINTER(ALchar) alGetString.argtypes = [ALenum] # /usr/include/AL/al.h:398 alGetBooleanv = _lib.alGetBooleanv alGetBooleanv.restype = None alGetBooleanv.argtypes = [ALenum, POINTER(ALboolean)] # /usr/include/AL/al.h:400 alGetIntegerv = _lib.alGetIntegerv alGetIntegerv.restype = None alGetIntegerv.argtypes = [ALenum, POINTER(ALint)] # /usr/include/AL/al.h:402 alGetFloatv = _lib.alGetFloatv alGetFloatv.restype = None alGetFloatv.argtypes = [ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:404 alGetDoublev = _lib.alGetDoublev alGetDoublev.restype = None alGetDoublev.argtypes = [ALenum, POINTER(ALdouble)] # /usr/include/AL/al.h:406 alGetBoolean = _lib.alGetBoolean alGetBoolean.restype = ALboolean alGetBoolean.argtypes = [ALenum] # /usr/include/AL/al.h:408 alGetInteger = _lib.alGetInteger alGetInteger.restype = ALint alGetInteger.argtypes = [ALenum] # /usr/include/AL/al.h:410 alGetFloat = _lib.alGetFloat alGetFloat.restype = ALfloat alGetFloat.argtypes = [ALenum] # /usr/include/AL/al.h:412 alGetDouble = _lib.alGetDouble alGetDouble.restype = ALdouble alGetDouble.argtypes = [ALenum] # /usr/include/AL/al.h:419 alGetError = _lib.alGetError alGetError.restype = ALenum alGetError.argtypes = [] # /usr/include/AL/al.h:427 alIsExtensionPresent = _lib.alIsExtensionPresent alIsExtensionPresent.restype = ALboolean alIsExtensionPresent.argtypes = [POINTER(ALchar)] # /usr/include/AL/al.h:429 alGetProcAddress = _lib.alGetProcAddress alGetProcAddress.restype = POINTER(c_void) alGetProcAddress.argtypes = [POINTER(ALchar)] # /usr/include/AL/al.h:431 alGetEnumValue = _lib.alGetEnumValue alGetEnumValue.restype = ALenum alGetEnumValue.argtypes = [POINTER(ALchar)] # /usr/include/AL/al.h:450 alListenerf = _lib.alListenerf alListenerf.restype = None alListenerf.argtypes = [ALenum, ALfloat] # /usr/include/AL/al.h:452 alListener3f = _lib.alListener3f alListener3f.restype = None alListener3f.argtypes = [ALenum, ALfloat, ALfloat, ALfloat] # /usr/include/AL/al.h:454 alListenerfv = _lib.alListenerfv alListenerfv.restype = None alListenerfv.argtypes = [ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:456 alListeneri = _lib.alListeneri alListeneri.restype = None alListeneri.argtypes = [ALenum, ALint] # /usr/include/AL/al.h:458 #alListener3i = _lib.alListener3i #alListener3i.restype = None #alListener3i.argtypes = [ALenum, ALint, ALint, ALint] # /usr/include/AL/al.h:460 #alListeneriv = _lib.alListeneriv #alListeneriv.restype = None #alListeneriv.argtypes = [ALenum, POINTER(ALint)] # /usr/include/AL/al.h:465 alGetListenerf = _lib.alGetListenerf alGetListenerf.restype = None alGetListenerf.argtypes = [ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:467 alGetListener3f = _lib.alGetListener3f alGetListener3f.restype = None alGetListener3f.argtypes = [ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)] # /usr/include/AL/al.h:469 alGetListenerfv = _lib.alGetListenerfv alGetListenerfv.restype = None alGetListenerfv.argtypes = [ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:471 alGetListeneri = _lib.alGetListeneri alGetListeneri.restype = None alGetListeneri.argtypes = [ALenum, POINTER(ALint)] # /usr/include/AL/al.h:473 alGetListener3i = _lib.alGetListener3i alGetListener3i.restype = None alGetListener3i.argtypes = [ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)] # /usr/include/AL/al.h:475 alGetListeneriv = _lib.alGetListeneriv alGetListeneriv.restype = None alGetListeneriv.argtypes = [ALenum, POINTER(ALint)] # /usr/include/AL/al.h:512 alGenSources = _lib.alGenSources alGenSources.restype = None alGenSources.argtypes = [ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:515 alDeleteSources = _lib.alDeleteSources alDeleteSources.restype = None alDeleteSources.argtypes = [ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:518 alIsSource = _lib.alIsSource alIsSource.restype = ALboolean alIsSource.argtypes = [ALuint] # /usr/include/AL/al.h:523 alSourcef = _lib.alSourcef alSourcef.restype = None alSourcef.argtypes = [ALuint, ALenum, ALfloat] # /usr/include/AL/al.h:525 alSource3f = _lib.alSource3f alSource3f.restype = None alSource3f.argtypes = [ALuint, ALenum, ALfloat, ALfloat, ALfloat] # /usr/include/AL/al.h:527 alSourcefv = _lib.alSourcefv alSourcefv.restype = None alSourcefv.argtypes = [ALuint, ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:529 alSourcei = _lib.alSourcei alSourcei.restype = None alSourcei.argtypes = [ALuint, ALenum, ALint] # /usr/include/AL/al.h:531 #alSource3i = _lib.alSource3i #alSource3i.restype = None #alSource3i.argtypes = [ALuint, ALenum, ALint, ALint, ALint] # /usr/include/AL/al.h:533 #alSourceiv = _lib.alSourceiv #alSourceiv.restype = None #alSourceiv.argtypes = [ALuint, ALenum, POINTER(ALint)] # /usr/include/AL/al.h:538 alGetSourcef = _lib.alGetSourcef alGetSourcef.restype = None alGetSourcef.argtypes = [ALuint, ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:540 alGetSource3f = _lib.alGetSource3f alGetSource3f.restype = None alGetSource3f.argtypes = [ALuint, ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)] # /usr/include/AL/al.h:542 alGetSourcefv = _lib.alGetSourcefv alGetSourcefv.restype = None alGetSourcefv.argtypes = [ALuint, ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:544 alGetSourcei = _lib.alGetSourcei alGetSourcei.restype = None alGetSourcei.argtypes = [ALuint, ALenum, POINTER(ALint)] # /usr/include/AL/al.h:546 #alGetSource3i = _lib.alGetSource3i #alGetSource3i.restype = None #alGetSource3i.argtypes = [ALuint, ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)] # /usr/include/AL/al.h:548 alGetSourceiv = _lib.alGetSourceiv alGetSourceiv.restype = None alGetSourceiv.argtypes = [ALuint, ALenum, POINTER(ALint)] # /usr/include/AL/al.h:556 alSourcePlayv = _lib.alSourcePlayv alSourcePlayv.restype = None alSourcePlayv.argtypes = [ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:559 alSourceStopv = _lib.alSourceStopv alSourceStopv.restype = None alSourceStopv.argtypes = [ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:562 alSourceRewindv = _lib.alSourceRewindv alSourceRewindv.restype = None alSourceRewindv.argtypes = [ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:565 alSourcePausev = _lib.alSourcePausev alSourcePausev.restype = None alSourcePausev.argtypes = [ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:572 alSourcePlay = _lib.alSourcePlay alSourcePlay.restype = None alSourcePlay.argtypes = [ALuint] # /usr/include/AL/al.h:575 alSourceStop = _lib.alSourceStop alSourceStop.restype = None alSourceStop.argtypes = [ALuint] # /usr/include/AL/al.h:578 alSourceRewind = _lib.alSourceRewind alSourceRewind.restype = None alSourceRewind.argtypes = [ALuint] # /usr/include/AL/al.h:581 alSourcePause = _lib.alSourcePause alSourcePause.restype = None alSourcePause.argtypes = [ALuint] # /usr/include/AL/al.h:586 alSourceQueueBuffers = _lib.alSourceQueueBuffers alSourceQueueBuffers.restype = None alSourceQueueBuffers.argtypes = [ALuint, ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:588 alSourceUnqueueBuffers = _lib.alSourceUnqueueBuffers alSourceUnqueueBuffers.restype = None alSourceUnqueueBuffers.argtypes = [ALuint, ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:606 alGenBuffers = _lib.alGenBuffers alGenBuffers.restype = None alGenBuffers.argtypes = [ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:609 alDeleteBuffers = _lib.alDeleteBuffers alDeleteBuffers.restype = None alDeleteBuffers.argtypes = [ALsizei, POINTER(ALuint)] # /usr/include/AL/al.h:612 alIsBuffer = _lib.alIsBuffer alIsBuffer.restype = ALboolean alIsBuffer.argtypes = [ALuint] # /usr/include/AL/al.h:615 alBufferData = _lib.alBufferData alBufferData.restype = None alBufferData.argtypes = [ALuint, ALenum, POINTER(ALvoid), ALsizei, ALsizei] # /usr/include/AL/al.h:620 alBufferf = _lib.alBufferf alBufferf.restype = None alBufferf.argtypes = [ALuint, ALenum, ALfloat] # /usr/include/AL/al.h:622 alBuffer3f = _lib.alBuffer3f alBuffer3f.restype = None alBuffer3f.argtypes = [ALuint, ALenum, ALfloat, ALfloat, ALfloat] # /usr/include/AL/al.h:624 alBufferfv = _lib.alBufferfv alBufferfv.restype = None alBufferfv.argtypes = [ALuint, ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:626 alBufferi = _lib.alBufferi alBufferi.restype = None alBufferi.argtypes = [ALuint, ALenum, ALint] # /usr/include/AL/al.h:628 alBuffer3i = _lib.alBuffer3i alBuffer3i.restype = None alBuffer3i.argtypes = [ALuint, ALenum, ALint, ALint, ALint] # /usr/include/AL/al.h:630 alBufferiv = _lib.alBufferiv alBufferiv.restype = None alBufferiv.argtypes = [ALuint, ALenum, POINTER(ALint)] # /usr/include/AL/al.h:635 alGetBufferf = _lib.alGetBufferf alGetBufferf.restype = None alGetBufferf.argtypes = [ALuint, ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:637 alGetBuffer3f = _lib.alGetBuffer3f alGetBuffer3f.restype = None alGetBuffer3f.argtypes = [ALuint, ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)] # /usr/include/AL/al.h:639 alGetBufferfv = _lib.alGetBufferfv alGetBufferfv.restype = None alGetBufferfv.argtypes = [ALuint, ALenum, POINTER(ALfloat)] # /usr/include/AL/al.h:641 alGetBufferi = _lib.alGetBufferi alGetBufferi.restype = None alGetBufferi.argtypes = [ALuint, ALenum, POINTER(ALint)] # /usr/include/AL/al.h:643 alGetBuffer3i = _lib.alGetBuffer3i alGetBuffer3i.restype = None alGetBuffer3i.argtypes = [ALuint, ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)] # /usr/include/AL/al.h:645 alGetBufferiv = _lib.alGetBufferiv alGetBufferiv.restype = None alGetBufferiv.argtypes = [ALuint, ALenum, POINTER(ALint)] # /usr/include/AL/al.h:651 alDopplerFactor = _lib.alDopplerFactor alDopplerFactor.restype = None alDopplerFactor.argtypes = [ALfloat] # /usr/include/AL/al.h:653 alDopplerVelocity = _lib.alDopplerVelocity alDopplerVelocity.restype = None alDopplerVelocity.argtypes = [ALfloat] # /usr/include/AL/al.h:655 alSpeedOfSound = _lib.alSpeedOfSound alSpeedOfSound.restype = None alSpeedOfSound.argtypes = [ALfloat] # /usr/include/AL/al.h:657 alDistanceModel = _lib.alDistanceModel alDistanceModel.restype = None alDistanceModel.argtypes = [ALenum] LPALENABLE = CFUNCTYPE(None, ALenum) # /usr/include/AL/al.h:662 LPALDISABLE = CFUNCTYPE(None, ALenum) # /usr/include/AL/al.h:663 LPALISENABLED = CFUNCTYPE(ALboolean, ALenum) # /usr/include/AL/al.h:664 LPALGETSTRING = CFUNCTYPE(POINTER(ALchar), ALenum) # /usr/include/AL/al.h:665 LPALGETBOOLEANV = CFUNCTYPE(None, ALenum, POINTER(ALboolean)) # /usr/include/AL/al.h:666 LPALGETINTEGERV = CFUNCTYPE(None, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:667 LPALGETFLOATV = CFUNCTYPE(None, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:668 LPALGETDOUBLEV = CFUNCTYPE(None, ALenum, POINTER(ALdouble)) # /usr/include/AL/al.h:669 LPALGETBOOLEAN = CFUNCTYPE(ALboolean, ALenum) # /usr/include/AL/al.h:670 LPALGETINTEGER = CFUNCTYPE(ALint, ALenum) # /usr/include/AL/al.h:671 LPALGETFLOAT = CFUNCTYPE(ALfloat, ALenum) # /usr/include/AL/al.h:672 LPALGETDOUBLE = CFUNCTYPE(ALdouble, ALenum) # /usr/include/AL/al.h:673 LPALGETERROR = CFUNCTYPE(ALenum) # /usr/include/AL/al.h:674 LPALISEXTENSIONPRESENT = CFUNCTYPE(ALboolean, POINTER(ALchar)) # /usr/include/AL/al.h:675 LPALGETPROCADDRESS = CFUNCTYPE(POINTER(c_void), POINTER(ALchar)) # /usr/include/AL/al.h:676 LPALGETENUMVALUE = CFUNCTYPE(ALenum, POINTER(ALchar)) # /usr/include/AL/al.h:677 LPALLISTENERF = CFUNCTYPE(None, ALenum, ALfloat) # /usr/include/AL/al.h:678 LPALLISTENER3F = CFUNCTYPE(None, ALenum, ALfloat, ALfloat, ALfloat) # /usr/include/AL/al.h:679 LPALLISTENERFV = CFUNCTYPE(None, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:680 LPALLISTENERI = CFUNCTYPE(None, ALenum, ALint) # /usr/include/AL/al.h:681 LPALLISTENER3I = CFUNCTYPE(None, ALenum, ALint, ALint, ALint) # /usr/include/AL/al.h:682 LPALLISTENERIV = CFUNCTYPE(None, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:683 LPALGETLISTENERF = CFUNCTYPE(None, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:684 LPALGETLISTENER3F = CFUNCTYPE(None, ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)) # /usr/include/AL/al.h:685 LPALGETLISTENERFV = CFUNCTYPE(None, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:686 LPALGETLISTENERI = CFUNCTYPE(None, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:687 LPALGETLISTENER3I = CFUNCTYPE(None, ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)) # /usr/include/AL/al.h:688 LPALGETLISTENERIV = CFUNCTYPE(None, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:689 LPALGENSOURCES = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:690 LPALDELETESOURCES = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:691 LPALISSOURCE = CFUNCTYPE(ALboolean, ALuint) # /usr/include/AL/al.h:692 LPALSOURCEF = CFUNCTYPE(None, ALuint, ALenum, ALfloat) # /usr/include/AL/al.h:693 LPALSOURCE3F = CFUNCTYPE(None, ALuint, ALenum, ALfloat, ALfloat, ALfloat) # /usr/include/AL/al.h:694 LPALSOURCEFV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:695 LPALSOURCEI = CFUNCTYPE(None, ALuint, ALenum, ALint) # /usr/include/AL/al.h:696 LPALSOURCE3I = CFUNCTYPE(None, ALuint, ALenum, ALint, ALint, ALint) # /usr/include/AL/al.h:697 LPALSOURCEIV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:698 LPALGETSOURCEF = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:699 LPALGETSOURCE3F = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)) # /usr/include/AL/al.h:700 LPALGETSOURCEFV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:701 LPALGETSOURCEI = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:702 LPALGETSOURCE3I = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)) # /usr/include/AL/al.h:703 LPALGETSOURCEIV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:704 LPALSOURCEPLAYV = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:705 LPALSOURCESTOPV = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:706 LPALSOURCEREWINDV = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:707 LPALSOURCEPAUSEV = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:708 LPALSOURCEPLAY = CFUNCTYPE(None, ALuint) # /usr/include/AL/al.h:709 LPALSOURCESTOP = CFUNCTYPE(None, ALuint) # /usr/include/AL/al.h:710 LPALSOURCEREWIND = CFUNCTYPE(None, ALuint) # /usr/include/AL/al.h:711 LPALSOURCEPAUSE = CFUNCTYPE(None, ALuint) # /usr/include/AL/al.h:712 LPALSOURCEQUEUEBUFFERS = CFUNCTYPE(None, ALuint, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:713 LPALSOURCEUNQUEUEBUFFERS = CFUNCTYPE(None, ALuint, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:714 LPALGENBUFFERS = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:715 LPALDELETEBUFFERS = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:716 LPALISBUFFER = CFUNCTYPE(ALboolean, ALuint) # /usr/include/AL/al.h:717 LPALBUFFERDATA = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALvoid), ALsizei, ALsizei) # /usr/include/AL/al.h:718 LPALBUFFERF = CFUNCTYPE(None, ALuint, ALenum, ALfloat) # /usr/include/AL/al.h:719 LPALBUFFER3F = CFUNCTYPE(None, ALuint, ALenum, ALfloat, ALfloat, ALfloat) # /usr/include/AL/al.h:720 LPALBUFFERFV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:721 LPALBUFFERI = CFUNCTYPE(None, ALuint, ALenum, ALint) # /usr/include/AL/al.h:722 LPALBUFFER3I = CFUNCTYPE(None, ALuint, ALenum, ALint, ALint, ALint) # /usr/include/AL/al.h:723 LPALBUFFERIV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:724 LPALGETBUFFERF = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:725 LPALGETBUFFER3F = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)) # /usr/include/AL/al.h:726 LPALGETBUFFERFV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:727 LPALGETBUFFERI = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:728 LPALGETBUFFER3I = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)) # /usr/include/AL/al.h:729 LPALGETBUFFERIV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:730 LPALDOPPLERFACTOR = CFUNCTYPE(None, ALfloat) # /usr/include/AL/al.h:731 LPALDOPPLERVELOCITY = CFUNCTYPE(None, ALfloat) # /usr/include/AL/al.h:732 LPALSPEEDOFSOUND = CFUNCTYPE(None, ALfloat) # /usr/include/AL/al.h:733 LPALDISTANCEMODEL = CFUNCTYPE(None, ALenum) # /usr/include/AL/al.h:734 __all__ = ['AL_API', 'ALAPI', 'AL_INVALID', 'AL_ILLEGAL_ENUM', 'AL_ILLEGAL_COMMAND', 'ALboolean', 'ALchar', 'ALbyte', 'ALubyte', 'ALshort', 'ALushort', 'ALint', 'ALuint', 'ALsizei', 'ALenum', 'ALfloat', 'ALdouble', 'ALvoid', 'AL_NONE', 'AL_FALSE', 'AL_TRUE', 'AL_SOURCE_RELATIVE', 'AL_CONE_INNER_ANGLE', 'AL_CONE_OUTER_ANGLE', 'AL_PITCH', 'AL_POSITION', 'AL_DIRECTION', 'AL_VELOCITY', 'AL_LOOPING', 'AL_BUFFER', 'AL_GAIN', 'AL_MIN_GAIN', 'AL_MAX_GAIN', 'AL_ORIENTATION', 'AL_SOURCE_STATE', 'AL_INITIAL', 'AL_PLAYING', 'AL_PAUSED', 'AL_STOPPED', 'AL_BUFFERS_QUEUED', 'AL_BUFFERS_PROCESSED', 'AL_SEC_OFFSET', 'AL_SAMPLE_OFFSET', 'AL_BYTE_OFFSET', 'AL_SOURCE_TYPE', 'AL_STATIC', 'AL_STREAMING', 'AL_UNDETERMINED', 'AL_FORMAT_MONO8', 'AL_FORMAT_MONO16', 'AL_FORMAT_STEREO8', 'AL_FORMAT_STEREO16', 'AL_REFERENCE_DISTANCE', 'AL_ROLLOFF_FACTOR', 'AL_CONE_OUTER_GAIN', 'AL_MAX_DISTANCE', 'AL_FREQUENCY', 'AL_BITS', 'AL_CHANNELS', 'AL_SIZE', 'AL_UNUSED', 'AL_PENDING', 'AL_PROCESSED', 'AL_NO_ERROR', 'AL_INVALID_NAME', 'AL_INVALID_ENUM', 'AL_INVALID_VALUE', 'AL_INVALID_OPERATION', 'AL_OUT_OF_MEMORY', 'AL_VENDOR', 'AL_VERSION', 'AL_RENDERER', 'AL_EXTENSIONS', 'AL_DOPPLER_FACTOR', 'AL_DOPPLER_VELOCITY', 'AL_SPEED_OF_SOUND', 'AL_DISTANCE_MODEL', 'AL_INVERSE_DISTANCE', 'AL_INVERSE_DISTANCE_CLAMPED', 'AL_LINEAR_DISTANCE', 'AL_LINEAR_DISTANCE_CLAMPED', 'AL_EXPONENT_DISTANCE', 'AL_EXPONENT_DISTANCE_CLAMPED', 'alEnable', 'alDisable', 'alIsEnabled', 'alGetString', 'alGetBooleanv', 'alGetIntegerv', 'alGetFloatv', 'alGetDoublev', 'alGetBoolean', 'alGetInteger', 'alGetFloat', 'alGetDouble', 'alGetError', 'alIsExtensionPresent', 'alGetProcAddress', 'alGetEnumValue', 'alListenerf', 'alListener3f', 'alListenerfv', 'alListeneri', 'alListener3i', 'alListeneriv', 'alGetListenerf', 'alGetListener3f', 'alGetListenerfv', 'alGetListeneri', 'alGetListener3i', 'alGetListeneriv', 'alGenSources', 'alDeleteSources', 'alIsSource', 'alSourcef', 'alSource3f', 'alSourcefv', 'alSourcei', 'alSource3i', 'alSourceiv', 'alGetSourcef', 'alGetSource3f', 'alGetSourcefv', 'alGetSourcei', 'alGetSource3i', 'alGetSourceiv', 'alSourcePlayv', 'alSourceStopv', 'alSourceRewindv', 'alSourcePausev', 'alSourcePlay', 'alSourceStop', 'alSourceRewind', 'alSourcePause', 'alSourceQueueBuffers', 'alSourceUnqueueBuffers', 'alGenBuffers', 'alDeleteBuffers', 'alIsBuffer', 'alBufferData', 'alBufferf', 'alBuffer3f', 'alBufferfv', 'alBufferi', 'alBuffer3i', 'alBufferiv', 'alGetBufferf', 'alGetBuffer3f', 'alGetBufferfv', 'alGetBufferi', 'alGetBuffer3i', 'alGetBufferiv', 'alDopplerFactor', 'alDopplerVelocity', 'alSpeedOfSound', 'alDistanceModel', 'LPALENABLE', 'LPALDISABLE', 'LPALISENABLED', 'LPALGETSTRING', 'LPALGETBOOLEANV', 'LPALGETINTEGERV', 'LPALGETFLOATV', 'LPALGETDOUBLEV', 'LPALGETBOOLEAN', 'LPALGETINTEGER', 'LPALGETFLOAT', 'LPALGETDOUBLE', 'LPALGETERROR', 'LPALISEXTENSIONPRESENT', 'LPALGETPROCADDRESS', 'LPALGETENUMVALUE', 'LPALLISTENERF', 'LPALLISTENER3F', 'LPALLISTENERFV', 'LPALLISTENERI', 'LPALLISTENER3I', 'LPALLISTENERIV', 'LPALGETLISTENERF', 'LPALGETLISTENER3F', 'LPALGETLISTENERFV', 'LPALGETLISTENERI', 'LPALGETLISTENER3I', 'LPALGETLISTENERIV', 'LPALGENSOURCES', 'LPALDELETESOURCES', 'LPALISSOURCE', 'LPALSOURCEF', 'LPALSOURCE3F', 'LPALSOURCEFV', 'LPALSOURCEI', 'LPALSOURCE3I', 'LPALSOURCEIV', 'LPALGETSOURCEF', 'LPALGETSOURCE3F', 'LPALGETSOURCEFV', 'LPALGETSOURCEI', 'LPALGETSOURCE3I', 'LPALGETSOURCEIV', 'LPALSOURCEPLAYV', 'LPALSOURCESTOPV', 'LPALSOURCEREWINDV', 'LPALSOURCEPAUSEV', 'LPALSOURCEPLAY', 'LPALSOURCESTOP', 'LPALSOURCEREWIND', 'LPALSOURCEPAUSE', 'LPALSOURCEQUEUEBUFFERS', 'LPALSOURCEUNQUEUEBUFFERS', 'LPALGENBUFFERS', 'LPALDELETEBUFFERS', 'LPALISBUFFER', 'LPALBUFFERDATA', 'LPALBUFFERF', 'LPALBUFFER3F', 'LPALBUFFERFV', 'LPALBUFFERI', 'LPALBUFFER3I', 'LPALBUFFERIV', 'LPALGETBUFFERF', 'LPALGETBUFFER3F', 'LPALGETBUFFERFV', 'LPALGETBUFFERI', 'LPALGETBUFFER3I', 'LPALGETBUFFERIV', 'LPALDOPPLERFACTOR', 'LPALDOPPLERVELOCITY', 'LPALSPEEDOFSOUND', 'LPALDISTANCEMODEL']
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Wrapper for openal Generated with: ../tools/wraptypes/wrap.py /usr/include/AL/alc.h -lopenal -olib_alc.py .. Hacked to fix ALCvoid argtypes. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import ctypes from ctypes import * import sys import pyglet.lib _lib = pyglet.lib.load_library('openal', win32='openal32', framework='/System/Library/Frameworks/OpenAL.framework') _int_types = (c_int16, c_int32) if hasattr(ctypes, 'c_int64'): # Some builds of ctypes apparently do not have c_int64 # defined; it's a pretty good bet that these builds do not # have 64-bit pointers. _int_types += (ctypes.c_int64,) for t in _int_types: if sizeof(t) == sizeof(c_size_t): c_ptrdiff_t = t class c_void(Structure): # c_void_p is a buggy return type, converting to int, so # POINTER(None) == c_void_p is actually written as # POINTER(c_void), so it can be treated as a real pointer. _fields_ = [('dummy', c_int)] ALC_API = 0 # /usr/include/AL/alc.h:19 ALCAPI = 0 # /usr/include/AL/alc.h:37 ALC_INVALID = 0 # /usr/include/AL/alc.h:39 ALC_VERSION_0_1 = 1 # /usr/include/AL/alc.h:42 class struct_ALCdevice_struct(Structure): __slots__ = [ ] struct_ALCdevice_struct._fields_ = [ ('_opaque_struct', c_int) ] class struct_ALCdevice_struct(Structure): __slots__ = [ ] struct_ALCdevice_struct._fields_ = [ ('_opaque_struct', c_int) ] ALCdevice = struct_ALCdevice_struct # /usr/include/AL/alc.h:44 class struct_ALCcontext_struct(Structure): __slots__ = [ ] struct_ALCcontext_struct._fields_ = [ ('_opaque_struct', c_int) ] class struct_ALCcontext_struct(Structure): __slots__ = [ ] struct_ALCcontext_struct._fields_ = [ ('_opaque_struct', c_int) ] ALCcontext = struct_ALCcontext_struct # /usr/include/AL/alc.h:45 ALCboolean = c_char # /usr/include/AL/alc.h:49 ALCchar = c_char # /usr/include/AL/alc.h:52 ALCbyte = c_char # /usr/include/AL/alc.h:55 ALCubyte = c_ubyte # /usr/include/AL/alc.h:58 ALCshort = c_short # /usr/include/AL/alc.h:61 ALCushort = c_ushort # /usr/include/AL/alc.h:64 ALCint = c_int # /usr/include/AL/alc.h:67 ALCuint = c_uint # /usr/include/AL/alc.h:70 ALCsizei = c_int # /usr/include/AL/alc.h:73 ALCenum = c_int # /usr/include/AL/alc.h:76 ALCfloat = c_float # /usr/include/AL/alc.h:79 ALCdouble = c_double # /usr/include/AL/alc.h:82 ALCvoid = None # /usr/include/AL/alc.h:85 ALC_FALSE = 0 # /usr/include/AL/alc.h:91 ALC_TRUE = 1 # /usr/include/AL/alc.h:94 ALC_FREQUENCY = 4103 # /usr/include/AL/alc.h:99 ALC_REFRESH = 4104 # /usr/include/AL/alc.h:104 ALC_SYNC = 4105 # /usr/include/AL/alc.h:109 ALC_MONO_SOURCES = 4112 # /usr/include/AL/alc.h:114 ALC_STEREO_SOURCES = 4113 # /usr/include/AL/alc.h:119 ALC_NO_ERROR = 0 # /usr/include/AL/alc.h:128 ALC_INVALID_DEVICE = 40961 # /usr/include/AL/alc.h:133 ALC_INVALID_CONTEXT = 40962 # /usr/include/AL/alc.h:138 ALC_INVALID_ENUM = 40963 # /usr/include/AL/alc.h:143 ALC_INVALID_VALUE = 40964 # /usr/include/AL/alc.h:148 ALC_OUT_OF_MEMORY = 40965 # /usr/include/AL/alc.h:153 ALC_DEFAULT_DEVICE_SPECIFIER = 4100 # /usr/include/AL/alc.h:159 ALC_DEVICE_SPECIFIER = 4101 # /usr/include/AL/alc.h:160 ALC_EXTENSIONS = 4102 # /usr/include/AL/alc.h:161 ALC_MAJOR_VERSION = 4096 # /usr/include/AL/alc.h:163 ALC_MINOR_VERSION = 4097 # /usr/include/AL/alc.h:164 ALC_ATTRIBUTES_SIZE = 4098 # /usr/include/AL/alc.h:166 ALC_ALL_ATTRIBUTES = 4099 # /usr/include/AL/alc.h:167 ALC_CAPTURE_DEVICE_SPECIFIER = 784 # /usr/include/AL/alc.h:172 ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER = 785 # /usr/include/AL/alc.h:173 ALC_CAPTURE_SAMPLES = 786 # /usr/include/AL/alc.h:174 # /usr/include/AL/alc.h:180 alcCreateContext = _lib.alcCreateContext alcCreateContext.restype = POINTER(ALCcontext) alcCreateContext.argtypes = [POINTER(ALCdevice), POINTER(ALCint)] # /usr/include/AL/alc.h:182 alcMakeContextCurrent = _lib.alcMakeContextCurrent alcMakeContextCurrent.restype = ALCboolean alcMakeContextCurrent.argtypes = [POINTER(ALCcontext)] # /usr/include/AL/alc.h:184 alcProcessContext = _lib.alcProcessContext alcProcessContext.restype = None alcProcessContext.argtypes = [POINTER(ALCcontext)] # /usr/include/AL/alc.h:186 alcSuspendContext = _lib.alcSuspendContext alcSuspendContext.restype = None alcSuspendContext.argtypes = [POINTER(ALCcontext)] # /usr/include/AL/alc.h:188 alcDestroyContext = _lib.alcDestroyContext alcDestroyContext.restype = None alcDestroyContext.argtypes = [POINTER(ALCcontext)] # /usr/include/AL/alc.h:190 alcGetCurrentContext = _lib.alcGetCurrentContext alcGetCurrentContext.restype = POINTER(ALCcontext) alcGetCurrentContext.argtypes = [] # /usr/include/AL/alc.h:192 alcGetContextsDevice = _lib.alcGetContextsDevice alcGetContextsDevice.restype = POINTER(ALCdevice) alcGetContextsDevice.argtypes = [POINTER(ALCcontext)] # /usr/include/AL/alc.h:198 alcOpenDevice = _lib.alcOpenDevice alcOpenDevice.restype = POINTER(ALCdevice) alcOpenDevice.argtypes = [POINTER(ALCchar)] # /usr/include/AL/alc.h:200 alcCloseDevice = _lib.alcCloseDevice alcCloseDevice.restype = ALCboolean alcCloseDevice.argtypes = [POINTER(ALCdevice)] # /usr/include/AL/alc.h:207 alcGetError = _lib.alcGetError alcGetError.restype = ALCenum alcGetError.argtypes = [POINTER(ALCdevice)] # /usr/include/AL/alc.h:215 alcIsExtensionPresent = _lib.alcIsExtensionPresent alcIsExtensionPresent.restype = ALCboolean alcIsExtensionPresent.argtypes = [POINTER(ALCdevice), POINTER(ALCchar)] # /usr/include/AL/alc.h:217 alcGetProcAddress = _lib.alcGetProcAddress alcGetProcAddress.restype = POINTER(c_void) alcGetProcAddress.argtypes = [POINTER(ALCdevice), POINTER(ALCchar)] # /usr/include/AL/alc.h:219 alcGetEnumValue = _lib.alcGetEnumValue alcGetEnumValue.restype = ALCenum alcGetEnumValue.argtypes = [POINTER(ALCdevice), POINTER(ALCchar)] # /usr/include/AL/alc.h:225 alcGetString = _lib.alcGetString alcGetString.restype = POINTER(ALCchar) alcGetString.argtypes = [POINTER(ALCdevice), ALCenum] # /usr/include/AL/alc.h:227 alcGetIntegerv = _lib.alcGetIntegerv alcGetIntegerv.restype = None alcGetIntegerv.argtypes = [POINTER(ALCdevice), ALCenum, ALCsizei, POINTER(ALCint)] # /usr/include/AL/alc.h:233 alcCaptureOpenDevice = _lib.alcCaptureOpenDevice alcCaptureOpenDevice.restype = POINTER(ALCdevice) alcCaptureOpenDevice.argtypes = [POINTER(ALCchar), ALCuint, ALCenum, ALCsizei] # /usr/include/AL/alc.h:235 alcCaptureCloseDevice = _lib.alcCaptureCloseDevice alcCaptureCloseDevice.restype = ALCboolean alcCaptureCloseDevice.argtypes = [POINTER(ALCdevice)] # /usr/include/AL/alc.h:237 alcCaptureStart = _lib.alcCaptureStart alcCaptureStart.restype = None alcCaptureStart.argtypes = [POINTER(ALCdevice)] # /usr/include/AL/alc.h:239 alcCaptureStop = _lib.alcCaptureStop alcCaptureStop.restype = None alcCaptureStop.argtypes = [POINTER(ALCdevice)] # /usr/include/AL/alc.h:241 alcCaptureSamples = _lib.alcCaptureSamples alcCaptureSamples.restype = None alcCaptureSamples.argtypes = [POINTER(ALCdevice), POINTER(ALCvoid), ALCsizei] LPALCCREATECONTEXT = CFUNCTYPE(POINTER(ALCcontext), POINTER(ALCdevice), POINTER(ALCint)) # /usr/include/AL/alc.h:246 LPALCMAKECONTEXTCURRENT = CFUNCTYPE(ALCboolean, POINTER(ALCcontext)) # /usr/include/AL/alc.h:247 LPALCPROCESSCONTEXT = CFUNCTYPE(None, POINTER(ALCcontext)) # /usr/include/AL/alc.h:248 LPALCSUSPENDCONTEXT = CFUNCTYPE(None, POINTER(ALCcontext)) # /usr/include/AL/alc.h:249 LPALCDESTROYCONTEXT = CFUNCTYPE(None, POINTER(ALCcontext)) # /usr/include/AL/alc.h:250 LPALCGETCURRENTCONTEXT = CFUNCTYPE(POINTER(ALCcontext)) # /usr/include/AL/alc.h:251 LPALCGETCONTEXTSDEVICE = CFUNCTYPE(POINTER(ALCdevice), POINTER(ALCcontext)) # /usr/include/AL/alc.h:252 LPALCOPENDEVICE = CFUNCTYPE(POINTER(ALCdevice), POINTER(ALCchar)) # /usr/include/AL/alc.h:253 LPALCCLOSEDEVICE = CFUNCTYPE(ALCboolean, POINTER(ALCdevice)) # /usr/include/AL/alc.h:254 LPALCGETERROR = CFUNCTYPE(ALCenum, POINTER(ALCdevice)) # /usr/include/AL/alc.h:255 LPALCISEXTENSIONPRESENT = CFUNCTYPE(ALCboolean, POINTER(ALCdevice), POINTER(ALCchar)) # /usr/include/AL/alc.h:256 LPALCGETPROCADDRESS = CFUNCTYPE(POINTER(c_void), POINTER(ALCdevice), POINTER(ALCchar)) # /usr/include/AL/alc.h:257 LPALCGETENUMVALUE = CFUNCTYPE(ALCenum, POINTER(ALCdevice), POINTER(ALCchar)) # /usr/include/AL/alc.h:258 LPALCGETSTRING = CFUNCTYPE(POINTER(ALCchar), POINTER(ALCdevice), ALCenum) # /usr/include/AL/alc.h:259 LPALCGETINTEGERV = CFUNCTYPE(None, POINTER(ALCdevice), ALCenum, ALCsizei, POINTER(ALCint)) # /usr/include/AL/alc.h:260 LPALCCAPTUREOPENDEVICE = CFUNCTYPE(POINTER(ALCdevice), POINTER(ALCchar), ALCuint, ALCenum, ALCsizei) # /usr/include/AL/alc.h:261 LPALCCAPTURECLOSEDEVICE = CFUNCTYPE(ALCboolean, POINTER(ALCdevice)) # /usr/include/AL/alc.h:262 LPALCCAPTURESTART = CFUNCTYPE(None, POINTER(ALCdevice)) # /usr/include/AL/alc.h:263 LPALCCAPTURESTOP = CFUNCTYPE(None, POINTER(ALCdevice)) # /usr/include/AL/alc.h:264 LPALCCAPTURESAMPLES = CFUNCTYPE(None, POINTER(ALCdevice), POINTER(ALCvoid), ALCsizei) # /usr/include/AL/alc.h:265 __all__ = ['ALC_API', 'ALCAPI', 'ALC_INVALID', 'ALC_VERSION_0_1', 'ALCdevice', 'ALCcontext', 'ALCboolean', 'ALCchar', 'ALCbyte', 'ALCubyte', 'ALCshort', 'ALCushort', 'ALCint', 'ALCuint', 'ALCsizei', 'ALCenum', 'ALCfloat', 'ALCdouble', 'ALCvoid', 'ALC_FALSE', 'ALC_TRUE', 'ALC_FREQUENCY', 'ALC_REFRESH', 'ALC_SYNC', 'ALC_MONO_SOURCES', 'ALC_STEREO_SOURCES', 'ALC_NO_ERROR', 'ALC_INVALID_DEVICE', 'ALC_INVALID_CONTEXT', 'ALC_INVALID_ENUM', 'ALC_INVALID_VALUE', 'ALC_OUT_OF_MEMORY', 'ALC_DEFAULT_DEVICE_SPECIFIER', 'ALC_DEVICE_SPECIFIER', 'ALC_EXTENSIONS', 'ALC_MAJOR_VERSION', 'ALC_MINOR_VERSION', 'ALC_ATTRIBUTES_SIZE', 'ALC_ALL_ATTRIBUTES', 'ALC_CAPTURE_DEVICE_SPECIFIER', 'ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER', 'ALC_CAPTURE_SAMPLES', 'alcCreateContext', 'alcMakeContextCurrent', 'alcProcessContext', 'alcSuspendContext', 'alcDestroyContext', 'alcGetCurrentContext', 'alcGetContextsDevice', 'alcOpenDevice', 'alcCloseDevice', 'alcGetError', 'alcIsExtensionPresent', 'alcGetProcAddress', 'alcGetEnumValue', 'alcGetString', 'alcGetIntegerv', 'alcCaptureOpenDevice', 'alcCaptureCloseDevice', 'alcCaptureStart', 'alcCaptureStop', 'alcCaptureSamples', 'LPALCCREATECONTEXT', 'LPALCMAKECONTEXTCURRENT', 'LPALCPROCESSCONTEXT', 'LPALCSUSPENDCONTEXT', 'LPALCDESTROYCONTEXT', 'LPALCGETCURRENTCONTEXT', 'LPALCGETCONTEXTSDEVICE', 'LPALCOPENDEVICE', 'LPALCCLOSEDEVICE', 'LPALCGETERROR', 'LPALCISEXTENSIONPRESENT', 'LPALCGETPROCADDRESS', 'LPALCGETENUMVALUE', 'LPALCGETSTRING', 'LPALCGETINTEGERV', 'LPALCCAPTUREOPENDEVICE', 'LPALCCAPTURECLOSEDEVICE', 'LPALCCAPTURESTART', 'LPALCCAPTURESTOP', 'LPALCCAPTURESAMPLES']
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id$ import ctypes import heapq import threading import time import Queue import atexit import lib_openal as al import lib_alc as alc from pyglet.media import MediaException, MediaEvent, AbstractAudioPlayer, \ AbstractAudioDriver, AbstractListener, MediaThread import pyglet _debug = pyglet.options['debug_media'] _debug_buffers = pyglet.options.get('debug_media_buffers', False) class OpenALException(MediaException): pass # TODO move functions into context/driver? def _split_nul_strings(s): # NUL-separated list of strings, double-NUL-terminated. nul = False i = 0 while True: if s[i] == '\0': if nul: break else: nul = True else: nul = False i += 1 s = s[:i - 1] return filter(None, [ss.strip() for ss in s.split('\0')]) format_map = { (1, 8): al.AL_FORMAT_MONO8, (1, 16): al.AL_FORMAT_MONO16, (2, 8): al.AL_FORMAT_STEREO8, (2, 16): al.AL_FORMAT_STEREO16, } class OpenALWorker(MediaThread): # Minimum size to bother refilling (bytes) _min_write_size = 512 # Time to wait if there are players, but they're all full. _nap_time = 0.05 # Time to wait if there are no players. _sleep_time = None def __init__(self): super(OpenALWorker, self).__init__() self.players = set() def run(self): while True: # This is a big lock, but ensures a player is not deleted while # we're processing it -- this saves on extra checks in the # player's methods that would otherwise have to check that it's # still alive. self.condition.acquire() if self.stopped: self.condition.release() break sleep_time = -1 # Refill player with least write_size if self.players: player = None write_size = 0 for p in self.players: s = p.get_write_size() if s > write_size: player = p write_size = s if write_size > self._min_write_size: player.refill(write_size) else: sleep_time = self._nap_time else: sleep_time = self._sleep_time self.condition.release() if sleep_time != -1: self.sleep(sleep_time) else: # We MUST sleep, or we will starve pyglet's main loop. It # also looks like if we don't sleep enough, we'll starve out # various updates that stop us from properly removing players # that should be removed. time.sleep(self._nap_time) def add(self, player): self.condition.acquire() self.players.add(player) self.condition.notify() self.condition.release() def remove(self, player): self.condition.acquire() if player in self.players: self.players.remove(player) self.condition.notify() self.condition.release() class OpenALBufferPool(object): """At least Mac OS X doesn't free buffers when a source is deleted; it just detaches them from the source. So keep our own recycled queue. """ def __init__(self): self._buffers = [] # list of free buffer names self._sources = {} # { sourceId : [ buffer names used ] } def getBuffer(self, alSource): """Convenience for returning one buffer name""" return self.getBuffers(alSource, 1)[0] def getBuffers(self, alSource, i): """Returns an array containing i buffer names. The returned list must not be modified in any way, and may get changed by subsequent calls to getBuffers. """ assert context._lock.locked() buffs = [] try: while i > 0: b = self._buffers.pop() if not al.alIsBuffer(b): # Protect against implementations that DO free buffers # when they delete a source - carry on. if _debug_buffers: print("Found a bad buffer") continue buffs.append(b) i -= 1 except IndexError: while i > 0: buffer = al.ALuint() al.alGenBuffers(1, buffer) if _debug_buffers: error = al.alGetError() if error != 0: print("GEN BUFFERS: " + str(error)) buffs.append(buffer) i -= 1 alSourceVal = alSource.value if alSourceVal not in self._sources: self._sources[alSourceVal] = buffs else: self._sources[alSourceVal].extend(buffs) return buffs def deleteSource(self, alSource): """Delete a source pointer (self._al_source) and free its buffers""" assert context._lock.locked() for buffer in self._sources.pop(alSource.value): self._buffers.append(buffer) def dequeueBuffer(self, alSource, buffer): """A buffer has finished playing, free it.""" assert context._lock.locked() sourceBuffs = self._sources[alSource.value] if buffer in sourceBuffs: sourceBuffs.remove(buffer) self._buffers.append(buffer) elif _debug_buffers: # This seems to be the problem with Mac OS X - The buffers are # dequeued, but they're not _actually_ buffers. In other words, # there's some leakage, so after awhile, things break. print("Bad buffer: " + str(buffer)) def delete(self): """Delete all sources and free all buffers""" assert context._lock.locked() for source, buffers in self._sources.items(): al.alDeleteSources(1, ctypes.byref(ctypes.c_uint(source))) for b in buffers: if not al.alIsBuffer(b): # Protect against implementations that DO free buffers # when they delete a source - carry on. if _debug_buffers: print("Found a bad buffer") continue al.alDeleteBuffers(1, ctypes.byref(b)) for b in self._buffers: al.alDeleteBuffers(1, ctypes.byref(b)) self._buffers = [] self._sources = {} bufferPool = OpenALBufferPool() class OpenALAudioPlayer(AbstractAudioPlayer): #: Minimum size of an OpenAL buffer worth bothering with, in bytes _min_buffer_size = 512 #: Aggregate (desired) buffer size, in bytes _ideal_buffer_size = 44800 def __init__(self, source_group, player): super(OpenALAudioPlayer, self).__init__(source_group, player) audio_format = source_group.audio_format try: self._al_format = format_map[(audio_format.channels, audio_format.sample_size)] except KeyError: raise OpenALException('Unsupported audio format.') self._al_source = al.ALuint() al.alGenSources(1, self._al_source) # Lock policy: lock all instance vars (except constants). (AL calls # are locked on context). self._lock = threading.RLock() # Cursor positions, like DSound and Pulse drivers, refer to a # hypothetical infinite-length buffer. Cursor units are in bytes. # Cursor position of current (head) AL buffer self._buffer_cursor = 0 # Estimated playback cursor position (last seen) self._play_cursor = 0 # Cursor position of end of queued AL buffer. self._write_cursor = 0 # List of currently queued buffer sizes (in bytes) self._buffer_sizes = [] # List of currently queued buffer timestamps self._buffer_timestamps = [] # Timestamp at end of last written buffer (timestamp to return in case # of underrun) self._underrun_timestamp = None # List of (cursor, MediaEvent) self._events = [] # Desired play state (True even if stopped due to underrun) self._playing = False # Has source group EOS been seen (and hence, event added to queue)? self._eos = False # OpenAL 1.0 timestamp interpolation: system time of current buffer # playback (best guess) if not context.have_1_1: self._buffer_system_time = time.time() self.refill(self._ideal_buffer_size) def __del__(self): try: self.delete() except: pass def delete(self): if _debug: print 'OpenALAudioPlayer.delete()' if not self._al_source: return context.worker.remove(self) self._lock.acquire() context.lock() al.alDeleteSources(1, self._al_source) bufferPool.deleteSource(self._al_source) if _debug_buffers: error = al.alGetError() if error != 0: print("DELETE ERROR: " + str(error)) context.unlock() self._al_source = None self._lock.release() def play(self): if self._playing: return if _debug: print 'OpenALAudioPlayer.play()' self._playing = True self._al_play() if not context.have_1_1: self._buffer_system_time = time.time() context.worker.add(self) def _al_play(self): if _debug: print 'OpenALAudioPlayer._al_play()' context.lock() state = al.ALint() al.alGetSourcei(self._al_source, al.AL_SOURCE_STATE, state) if state.value != al.AL_PLAYING: al.alSourcePlay(self._al_source) context.unlock() def stop(self): if not self._playing: return if _debug: print 'OpenALAudioPlayer.stop()' self._pause_timestamp = self.get_time() context.lock() al.alSourcePause(self._al_source) context.unlock() self._playing = False context.worker.remove(self) def clear(self): if _debug: print 'OpenALAudioPlayer.clear()' self._lock.acquire() context.lock() al.alSourceStop(self._al_source) self._playing = False del self._events[:] self._underrun_timestamp = None self._buffer_timestamps = [None for _ in self._buffer_timestamps] context.unlock() self._lock.release() def _update_play_cursor(self): if not self._al_source: return self._lock.acquire() context.lock() # Release spent buffers processed = al.ALint() al.alGetSourcei(self._al_source, al.AL_BUFFERS_PROCESSED, processed) processed = processed.value if processed: buffers = (al.ALuint * processed)() al.alSourceUnqueueBuffers(self._al_source, len(buffers), buffers) error = al.alGetError() if error != 0: if _debug_buffers: print("Source unqueue error: " + str(error)) else: for b in buffers: bufferPool.dequeueBuffer(self._al_source, b) context.unlock() if processed: if (len(self._buffer_timestamps) == processed and self._buffer_timestamps[-1] is not None): # Underrun, take note of timestamp. # We check that the timestamp is not None, because otherwise # our source could have been cleared. self._underrun_timestamp = \ self._buffer_timestamps[-1] + \ self._buffer_sizes[-1] / \ float(self.source_group.audio_format.bytes_per_second) self._buffer_cursor += sum(self._buffer_sizes[:processed]) del self._buffer_sizes[:processed] del self._buffer_timestamps[:processed] if not context.have_1_1: self._buffer_system_time = time.time() # Update play cursor using buffer cursor + estimate into current # buffer if context.have_1_1: bytes = al.ALint() context.lock() al.alGetSourcei(self._al_source, al.AL_BYTE_OFFSET, bytes) context.unlock() if _debug: print 'got bytes offset', bytes.value self._play_cursor = self._buffer_cursor + bytes.value else: # Interpolate system time past buffer timestamp self._play_cursor = \ self._buffer_cursor + int( (time.time() - self._buffer_system_time) * \ self.source_group.audio_format.bytes_per_second) # Process events while self._events and self._events[0][0] < self._play_cursor: _, event = self._events.pop(0) event._sync_dispatch_to_player(self.player) self._lock.release() def get_write_size(self): self._lock.acquire() self._update_play_cursor() write_size = self._ideal_buffer_size - \ (self._write_cursor - self._play_cursor) if self._eos: write_size = 0 self._lock.release() return write_size def refill(self, write_size): if _debug: print 'refill', write_size self._lock.acquire() while write_size > self._min_buffer_size: audio_data = self.source_group.get_audio_data(write_size) if not audio_data: self._eos = True self._events.append( (self._write_cursor, MediaEvent(0, 'on_eos'))) self._events.append( (self._write_cursor, MediaEvent(0, 'on_source_group_eos'))) break for event in audio_data.events: cursor = self._write_cursor + event.timestamp * \ self.source_group.audio_format.bytes_per_second self._events.append((cursor, event)) context.lock() buffer = bufferPool.getBuffer(self._al_source) al.alBufferData(buffer, self._al_format, audio_data.data, audio_data.length, self.source_group.audio_format.sample_rate) if _debug_buffers: error = al.alGetError() if error != 0: print("BUFFER DATA ERROR: " + str(error)) al.alSourceQueueBuffers(self._al_source, 1, ctypes.byref(buffer)) if _debug_buffers: error = al.alGetError() if error != 0: print("QUEUE BUFFER ERROR: " + str(error)) context.unlock() self._write_cursor += audio_data.length self._buffer_sizes.append(audio_data.length) self._buffer_timestamps.append(audio_data.timestamp) write_size -= audio_data.length # Check for underrun stopping playback if self._playing: state = al.ALint() context.lock() al.alGetSourcei(self._al_source, al.AL_SOURCE_STATE, state) if state.value != al.AL_PLAYING: if _debug: print 'underrun' al.alSourcePlay(self._al_source) context.unlock() self._lock.release() def get_time(self): try: buffer_timestamp = self._buffer_timestamps[0] except IndexError: return self._underrun_timestamp if buffer_timestamp is None: return None return buffer_timestamp + \ (self._play_cursor - self._buffer_cursor) / \ float(self.source_group.audio_format.bytes_per_second) def set_volume(self, volume): context.lock() al.alSourcef(self._al_source, al.AL_GAIN, max(0, volume)) context.unlock() def set_position(self, position): x, y, z = position context.lock() al.alSource3f(self._al_source, al.AL_POSITION, x, y, z) context.unlock() def set_min_distance(self, min_distance): context.lock() al.alSourcef(self._al_source, al.AL_REFERENCE_DISTANCE, min_distance) context.unlock() def set_max_distance(self, max_distance): context.lock() al.alSourcef(self._al_source, al.AL_MAX_DISTANCE, max_distance) context.unlock() def set_pitch(self, pitch): context.lock() al.alSourcef(self._al_source, al.AL_PITCH, max(0, pitch)) context.unlock() def set_cone_orientation(self, cone_orientation): x, y, z = cone_orientation context.lock() al.alSource3f(self._al_source, al.AL_DIRECTION, x, y, z) context.unlock() def set_cone_inner_angle(self, cone_inner_angle): context.lock() al.alSourcef(self._al_source, al.AL_CONE_INNER_ANGLE, cone_inner_angle) context.unlock() def set_cone_outer_angle(self, cone_outer_angle): context.lock() al.alSourcef(self._al_source, al.AL_CONE_OUTER_ANGLE, cone_outer_angle) context.unlock() def set_cone_outer_gain(self, cone_outer_gain): context.lock() al.alSourcef(self._al_source, al.AL_CONE_OUTER_GAIN, cone_outer_gain) context.unlock() class OpenALDriver(AbstractAudioDriver): _forward_orientation = (0, 0, -1) _up_orientation = (0, 1, 0) def __init__(self, device_name=None): super(OpenALDriver, self).__init__() # TODO devices must be enumerated on Windows, otherwise 1.0 context is # returned. self._device = alc.alcOpenDevice(device_name) if not self._device: raise Exception('No OpenAL device.') self._context = alc.alcCreateContext(self._device, None) alc.alcMakeContextCurrent(self._context) self.have_1_1 = self.have_version(1, 1) and False self._lock = threading.Lock() self._listener = OpenALListener(self) # Start worker thread self.worker = OpenALWorker() self.worker.start() def create_audio_player(self, source_group, player): assert self._device is not None, "Device was closed" return OpenALAudioPlayer(source_group, player) def delete(self): self.worker.stop() self.lock() alc.alcMakeContextCurrent(None) alc.alcDestroyContext(self._context) alc.alcCloseDevice(self._device) self._device = None self.unlock() def lock(self): self._lock.acquire() def unlock(self): self._lock.release() def have_version(self, major, minor): return (major, minor) <= self.get_version() def get_version(self): major = alc.ALCint() minor = alc.ALCint() alc.alcGetIntegerv(self._device, alc.ALC_MAJOR_VERSION, ctypes.sizeof(major), major) alc.alcGetIntegerv(self._device, alc.ALC_MINOR_VERSION, ctypes.sizeof(minor), minor) return major.value, minor.value def get_extensions(self): extensions = alc.alcGetString(self._device, alc.ALC_EXTENSIONS) if pyglet.compat_platform == 'darwin' or pyglet.compat_platform.startswith('linux'): return ctypes.cast(extensions, ctypes.c_char_p).value.split(' ') else: return _split_nul_strings(extensions) def have_extension(self, extension): return extension in self.get_extensions() def get_listener(self): return self._listener class OpenALListener(AbstractListener): def __init__(self, driver): self._driver = driver def _set_volume(self, volume): self._driver.lock() al.alListenerf(al.AL_GAIN, volume) self._driver.unlock() self._volume = volume def _set_position(self, position): x, y, z = position self._driver.lock() al.alListener3f(al.AL_POSITION, x, y, z) self._driver.unlock() self._position = position def _set_forward_orientation(self, orientation): val = (al.ALfloat * 6)(*(orientation + self._up_orientation)) self._driver.lock() al.alListenerfv(al.AL_ORIENTATION, val) self._driver.unlock() self._forward_orientation = orientation def _set_up_orientation(self, orientation): val = (al.ALfloat * 6)(*(self._forward_orientation + orientation)) self._driver.lock() al.alListenerfv(al.AL_ORIENTATION, val) self._driver.unlock() self._up_orientation = orientation context = None def create_audio_driver(device_name=None): global context context = OpenALDriver(device_name) if _debug: print 'OpenAL', context.get_version() return context def cleanup_audio_driver(): global context if _debug: print "Cleaning up audio driver" if context: context.lock() bufferPool.delete() context.unlock() context.delete() context = None if _debug: print "Cleaning done" atexit.register(cleanup_audio_driver)
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import time from pyglet.media import AbstractAudioPlayer, AbstractAudioDriver, \ MediaThread, MediaEvent import pyglet _debug = pyglet.options['debug_media'] class SilentAudioPacket(object): def __init__(self, timestamp, duration): self.timestamp = timestamp self.duration = duration def consume(self, dt): self.timestamp += dt self.duration -= dt class SilentAudioPlayerPacketConsumer(AbstractAudioPlayer): # When playing video, length of audio (in secs) to buffer ahead. _buffer_time = 0.4 # Minimum number of bytes to request from source _min_update_bytes = 1024 # Maximum sleep time _sleep_time = 0.2 def __init__(self, source_group, player): super(SilentAudioPlayerPacketConsumer, self).__init__(source_group, player) # System time of first timestamp self._timestamp_time = None # List of buffered SilentAudioPacket self._packets = [] self._packets_duration = 0 self._events = [] # Actual play state. self._playing = False # TODO Be nice to avoid creating this thread if user doesn't care # about EOS events and there's no video format. # NOTE Use thread.condition as lock for all instance vars used by worker self._thread = MediaThread(target=self._worker_func) if source_group.audio_format: self._thread.start() def delete(self): if _debug: print 'SilentAudioPlayer.delete' self._thread.stop() def play(self): if _debug: print 'SilentAudioPlayer.play' self._thread.condition.acquire() if not self._playing: self._playing = True self._timestamp_time = time.time() self._thread.condition.notify() self._thread.condition.release() def stop(self): if _debug: print 'SilentAudioPlayer.stop' self._thread.condition.acquire() if self._playing: timestamp = self.get_time() if self._packets: packet = self._packets[0] self._packets_duration -= timestamp - packet.timestamp packet.consume(timestamp - packet.timestamp) self._playing = False self._thread.condition.release() def clear(self): if _debug: print 'SilentAudioPlayer.clear' self._thread.condition.acquire() del self._packets[:] self._packets_duration = 0 del self._events[:] self._thread.condition.release() def get_time(self): if _debug: print 'SilentAudioPlayer.get_time()' self._thread.condition.acquire() packets = self._packets if self._playing: # Consume timestamps result = None offset = time.time() - self._timestamp_time while packets: packet = packets[0] if offset > packet.duration: del packets[0] self._timestamp_time += packet.duration offset -= packet.duration self._packets_duration -= packet.duration else: packet.consume(offset) self._packets_duration -= offset self._timestamp_time += offset result = packet.timestamp break else: # Paused if packets: result = packets[0].timestamp else: result = None self._thread.condition.release() if _debug: print 'SilentAudioPlayer.get_time() -> ', result return result # Worker func that consumes audio data and dispatches events def _worker_func(self): thread = self._thread #buffered_time = 0 eos = False events = self._events while True: thread.condition.acquire() if thread.stopped or (eos and not events): thread.condition.release() break # Use up "buffered" audio based on amount of time passed. timestamp = self.get_time() if _debug: print 'timestamp: %r' % timestamp # Dispatch events while events and timestamp is not None: if (events[0].timestamp is None or events[0].timestamp <= timestamp): events[0]._sync_dispatch_to_player(self.player) del events[0] # Calculate how much data to request from source secs = self._buffer_time - self._packets_duration bytes = secs * self.source_group.audio_format.bytes_per_second if _debug: print 'Trying to buffer %d bytes (%r secs)' % (bytes, secs) while bytes > self._min_update_bytes and not eos: # Pull audio data from source audio_data = self.source_group.get_audio_data(int(bytes)) if not audio_data and not eos: events.append(MediaEvent(timestamp, 'on_eos')) events.append(MediaEvent(timestamp, 'on_source_group_eos')) eos = True break # Pretend to buffer audio data, collect events. if self._playing and not self._packets: self._timestamp_time = time.time() self._packets.append(SilentAudioPacket(audio_data.timestamp, audio_data.duration)) self._packets_duration += audio_data.duration for event in audio_data.events: event.timestamp += audio_data.timestamp events.append(event) events.extend(audio_data.events) bytes -= audio_data.length sleep_time = self._sleep_time if not self._playing: sleep_time = None elif events and events[0].timestamp and timestamp: sleep_time = min(sleep_time, events[0].timestamp - timestamp) if _debug: print 'SilentAudioPlayer(Worker).sleep', sleep_time thread.sleep(sleep_time) thread.condition.release() class SilentTimeAudioPlayer(AbstractAudioPlayer): # Note that when using this player (automatic if playing back video with # unsupported audio codec) no events are dispatched (because they are # normally encoded in the audio packet -- so no EOS events are delivered. # This is a design flaw. # # Also, seeking is broken because the timestamps aren't synchronized with # the source group. _time = 0.0 _systime = None def play(self): self._systime = time.time() def stop(self): self._time = self.get_time() self._systime = None def delete(self): pass def clear(self): pass def get_time(self): if self._systime is None: return self._time else: return time.time() - self._systime + self._time class SilentAudioDriver(AbstractAudioDriver): def create_audio_player(self, source_group, player): if source_group.audio_format: return SilentAudioPlayerPacketConsumer(source_group, player) else: return SilentTimeAudioPlayer(source_group, player) def create_audio_driver(): return SilentAudioDriver()
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import sys import lib_pulseaudio as pa from pyglet.media import AbstractAudioDriver, AbstractAudioPlayer, \ AbstractListener, MediaException, MediaEvent import pyglet _debug = pyglet.options['debug_media'] def check(result): if result < 0: error = pa.pa_context_errno(context._context) raise MediaException(pa.pa_strerror(error)) return result def check_not_null(value): if not value: error = pa.pa_context_errno(context._context) raise MediaException(pa.pa_strerror(error)) return value class PulseAudioDriver(AbstractAudioDriver): _context = None def __init__(self): self.threaded_mainloop = pa.pa_threaded_mainloop_new() self.mainloop = pa.pa_threaded_mainloop_get_api( self.threaded_mainloop) self._players = pyglet.app.WeakSet() self._listener = PulseAudioListener(self) def create_audio_player(self, source_group, player): player = PulseAudioPlayer(source_group, player) self._players.add(player) return player def connect(self, server=None): '''Connect to pulseaudio server. :Parameters: `server` : str Server to connect to, or ``None`` for the default local server (which may be spawned as a daemon if no server is found). ''' # TODO disconnect from old assert not self._context, 'Already connected' # Create context app_name = self.get_app_name() self._context = pa.pa_context_new(self.mainloop, app_name.encode('ASCII')) # Context state callback self._state_cb_func = pa.pa_context_notify_cb_t(self._state_cb) pa.pa_context_set_state_callback(self._context, self._state_cb_func, None) # Connect check( pa.pa_context_connect(self._context, server, 0, None) ) self.lock() check( pa.pa_threaded_mainloop_start(self.threaded_mainloop) ) try: # Wait for context ready. self.wait() if pa.pa_context_get_state(self._context) != pa.PA_CONTEXT_READY: check(-1) finally: self.unlock() def _state_cb(self, context, userdata): if _debug: print 'context state cb' state = pa.pa_context_get_state(self._context) if state in (pa.PA_CONTEXT_READY, pa.PA_CONTEXT_TERMINATED, pa.PA_CONTEXT_FAILED): self.signal() def lock(self): '''Lock the threaded mainloop against events. Required for all calls into PA.''' pa.pa_threaded_mainloop_lock(self.threaded_mainloop) def unlock(self): '''Unlock the mainloop thread.''' pa.pa_threaded_mainloop_unlock(self.threaded_mainloop) def signal(self): '''Signal the mainloop thread to break from a wait.''' pa.pa_threaded_mainloop_signal(self.threaded_mainloop, 0) def wait(self): '''Wait for a signal.''' pa.pa_threaded_mainloop_wait(self.threaded_mainloop) def sync_operation(self, op): '''Wait for an operation to be done or cancelled, then release it. Uses a busy-loop -- make sure a callback is registered to signal this listener.''' while pa.pa_operation_get_state(op) == pa.PA_OPERATION_RUNNING: pa.pa_threaded_mainloop_wait(self.threaded_mainloop) pa.pa_operation_unref(op) def async_operation(self, op): '''Release the operation immediately without waiting for it to complete.''' pa.pa_operation_unref(op) def get_app_name(self): '''Get the application name as advertised to the pulseaudio server.''' # TODO move app name into pyglet.app (also useful for OS X menu bar?). return sys.argv[0] def dump_debug_info(self): print 'Client version: ', pa.pa_get_library_version() print 'Server: ', pa.pa_context_get_server(self._context) print 'Protocol: ', pa.pa_context_get_protocol_version( self._context) print 'Server protocol:', pa.pa_context_get_server_protocol_version( self._context) print 'Local context: ', ( pa.pa_context_is_local(self._context) and 'Yes' or 'No') def delete(self): '''Completely shut down pulseaudio client.''' self.lock() pa.pa_context_unref(self._context) self.unlock() pa.pa_threaded_mainloop_stop(self.threaded_mainloop) pa.pa_threaded_mainloop_free(self.threaded_mainloop) self.threaded_mainloop = None self.mainloop = None def get_listener(self): return self._listener class PulseAudioListener(AbstractListener): def __init__(self, driver): self.driver = driver def _set_volume(self, volume): self._volume = volume for player in self.driver._players: player.set_volume(player._volume) def _set_position(self, position): self._position = position def _set_forward_orientation(self, orientation): self._forward_orientation = orientation def _set_up_orientation(self, orientation): self._up_orientation = orientation class PulseAudioPlayer(AbstractAudioPlayer): _volume = 1.0 def __init__(self, source_group, player): super(PulseAudioPlayer, self).__init__(source_group, player) self._events = [] self._timestamps = [] # List of (ref_time, timestamp) self._write_index = 0 # Current write index (tracked manually) self._read_index_valid = False # True only if buffer has non-stale data self._clear_write = False self._buffered_audio_data = None self._underflow_is_eos = False self._playing = False audio_format = source_group.audio_format assert audio_format # Create sample_spec sample_spec = pa.pa_sample_spec() if audio_format.sample_size == 8: sample_spec.format = pa.PA_SAMPLE_U8 elif audio_format.sample_size == 16: if sys.byteorder == 'little': sample_spec.format = pa.PA_SAMPLE_S16LE else: sample_spec.format = pa.PA_SAMPLE_S16BE else: raise MediaException('Unsupported sample size') sample_spec.rate = audio_format.sample_rate sample_spec.channels = audio_format.channels channel_map = None self.sample_rate = audio_format.sample_rate try: context.lock() # Create stream self.stream = pa.pa_stream_new(context._context, str(id(self)).encode('ASCII'), sample_spec, channel_map) check_not_null(self.stream) # Callback trampoline for success operations self._success_cb_func = pa.pa_stream_success_cb_t(self._success_cb) self._context_success_cb_func = \ pa.pa_context_success_cb_t(self._context_success_cb) # Callback for underflow (to detect EOS when expected pa_timestamp # does not get reached). self._underflow_cb_func = \ pa.pa_stream_notify_cb_t(self._underflow_cb) pa.pa_stream_set_underflow_callback(self.stream, self._underflow_cb_func, None) # Callback for data write self._write_cb_func = pa.pa_stream_request_cb_t(self._write_cb) pa.pa_stream_set_write_callback(self.stream, self._write_cb_func, None) # Connect to sink device = None buffer_attr = None flags = (pa.PA_STREAM_START_CORKED | pa.PA_STREAM_INTERPOLATE_TIMING | pa.PA_STREAM_VARIABLE_RATE) sync_stream = None # TODO use this check( pa.pa_stream_connect_playback(self.stream, device, buffer_attr, flags, None, sync_stream) ) # Wait for stream readiness self._state_cb_func = pa.pa_stream_notify_cb_t(self._state_cb) pa.pa_stream_set_state_callback(self.stream, self._state_cb_func, None) while pa.pa_stream_get_state(self.stream) == pa.PA_STREAM_CREATING: context.wait() if pa.pa_stream_get_state(self.stream) != pa.PA_STREAM_READY: check(-1) finally: context.unlock() if _debug: print 'stream ready' def _state_cb(self, stream, data): context.signal() def _success_cb(self, stream, success, data): context.signal() def _context_success_cb(self, ctxt, success, data): context.signal() def _write_cb(self, stream, bytes, data): if _debug: print 'write callback: %d bytes' % bytes # Asynchronously update time if self._events: context.async_operation( pa.pa_stream_update_timing_info(self.stream, self._success_cb_func, None) ) # Grab next audio packet, or leftovers from last callback. if self._buffered_audio_data: audio_data = self._buffered_audio_data self._buffered_audio_data = None else: audio_data = self.source_group.get_audio_data(bytes) seek_flag = pa.PA_SEEK_RELATIVE if self._clear_write: if _debug: print 'seek PA_SEEK_RELATIVE_ON_READ' seek_flag = pa.PA_SEEK_RELATIVE_ON_READ self._clear_write = False # Keep writing packets until `bytes` is depleted while audio_data and bytes > 0: if _debug: print 'packet', audio_data.timestamp if _debug and audio_data.events: print 'events', audio_data.events for event in audio_data.events: event_index = self._write_index + event.timestamp * \ self.source_group.audio_format.bytes_per_second self._events.append((event_index, event)) consumption = min(bytes, audio_data.length) check( pa.pa_stream_write(self.stream, audio_data.data, consumption, pa.pa_free_cb_t(0), # Data is copied 0, seek_flag) ) seek_flag = pa.PA_SEEK_RELATIVE self._read_index_valid = True self._timestamps.append((self._write_index, audio_data.timestamp)) self._write_index += consumption self._underflow_is_eos = False if _debug: print 'write', consumption if consumption < audio_data.length: audio_data.consume(consumption, self.source_group.audio_format) self._buffered_audio_data = audio_data break bytes -= consumption if bytes > 0: audio_data = self.source_group.get_audio_data(bytes) #XXX name change if not audio_data: # Whole source group has been written. Any underflow encountered # after now is the EOS. self._underflow_is_eos = True # In case the source group wasn't long enough to prebuffer stream # to PA's satisfaction, trigger immediate playback (has no effect # if stream is already playing). if self._playing: context.async_operation( pa.pa_stream_trigger(self.stream, pa.pa_stream_success_cb_t(0), None) ) self._process_events() def _underflow_cb(self, stream, data): self._process_events() if self._underflow_is_eos: self._sync_dispatch_player_event('on_eos') self._sync_dispatch_player_event('on_source_group_eos') self._underflow_is_eos = False if _debug: print 'eos' else: if _debug: print 'underflow' # TODO: does PA automatically restart stream when buffered again? # XXX: sometimes receive an underflow after EOS... need to filter? def _process_events(self): if not self._events: return timing_info = pa.pa_stream_get_timing_info(self.stream) if not timing_info: if _debug: print 'abort _process_events' return read_index = timing_info.contents.read_index while self._events and self._events[0][0] < read_index: _, event = self._events.pop(0) if _debug: print 'dispatch event', event event._sync_dispatch_to_player(self.player) def _sync_dispatch_player_event(self, event, *args): pyglet.app.platform_event_loop.post_event(self.player, event, *args) def __del__(self): try: self.delete() except: pass def delete(self): if _debug: print 'delete' if not self.stream: return context.lock() pa.pa_stream_disconnect(self.stream) context.unlock() pa.pa_stream_unref(self.stream) self.stream = None def clear(self): if _debug: print 'clear' self._clear_write = True self._write_index = self._get_read_index() self._timestamps = [] self._events = [] context.lock() self._read_index_valid = False context.sync_operation( pa.pa_stream_prebuf(self.stream, self._success_cb_func, None) ) context.unlock() def play(self): if _debug: print 'play' context.lock() context.async_operation( pa.pa_stream_cork(self.stream, 0, pa.pa_stream_success_cb_t(0), None) ) # If whole stream has already been written, trigger immediate # playback. if self._underflow_is_eos: context.async_operation( pa.pa_stream_trigger(self.stream, pa.pa_stream_success_cb_t(0), None) ) context.unlock() self._playing = True def stop(self): if _debug: print 'stop' context.lock() context.async_operation( pa.pa_stream_cork(self.stream, 1, pa.pa_stream_success_cb_t(0), None) ) context.unlock() self._playing = False def _get_read_index(self): #time = pa.pa_usec_t() context.lock() context.sync_operation( pa.pa_stream_update_timing_info(self.stream, self._success_cb_func, None) ) context.unlock() timing_info = pa.pa_stream_get_timing_info(self.stream) if timing_info: read_index = timing_info.contents.read_index else: read_index = 0 if _debug: print '_get_read_index ->', read_index return read_index def _get_write_index(self): timing_info = pa.pa_stream_get_timing_info(self.stream) if timing_info: write_index = timing_info.contents.write_index else: write_index = 0 if _debug: print '_get_write_index ->', write_index return write_index def get_time(self): if not self._read_index_valid: if _debug: print 'get_time <_read_index_valid = False> -> None' return read_index = self._get_read_index() write_index = 0 timestamp = 0.0 try: write_index, timestamp = self._timestamps[0] write_index, timestamp = self._timestamps[1] while read_index >= write_index: del self._timestamps[0] write_index, timestamp = self._timestamps[1] except IndexError: pass bytes_per_second = self.source_group.audio_format.bytes_per_second time = timestamp + (read_index - write_index) / float(bytes_per_second) if _debug: print 'get_time ->', time return time def set_volume(self, volume): self._volume = volume if not self.stream: return volume *= context._listener._volume cvolume = pa.pa_cvolume() volume = pa.pa_sw_volume_from_linear(volume) pa.pa_cvolume_set(cvolume, self.source_group.audio_format.channels, volume) context.lock() idx = pa.pa_stream_get_index(self.stream) context.sync_operation( pa.pa_context_set_sink_input_volume(context._context, idx, cvolume, self._context_success_cb_func, None) ) context.unlock() def set_pitch(self, pitch): pa.pa_stream_update_sample_rate(self.stream, int(pitch*self.sample_rate), self._success_cb_func, None) def create_audio_driver(): global context context = PulseAudioDriver() context.connect() if _debug: context.dump_debug_info() return context
Python
'''Wrapper for pulse Generated with: tools/genwrappers.py pulseaudio Do not modify this file. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: wrap.py 1694 2008-01-30 23:12:00Z Alex.Holkner $' import ctypes from ctypes import * import pyglet.lib _lib = pyglet.lib.load_library('pulse') _int_types = (c_int16, c_int32) if hasattr(ctypes, 'c_int64'): # Some builds of ctypes apparently do not have c_int64 # defined; it's a pretty good bet that these builds do not # have 64-bit pointers. _int_types += (ctypes.c_int64,) for t in _int_types: if sizeof(t) == sizeof(c_size_t): c_ptrdiff_t = t class c_void(Structure): # c_void_p is a buggy return type, converting to int, so # POINTER(None) == c_void_p is actually written as # POINTER(c_void), so it can be treated as a real pointer. _fields_ = [('dummy', c_int)] class struct_pa_mainloop_api(Structure): __slots__ = [ ] struct_pa_mainloop_api._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_mainloop_api(Structure): __slots__ = [ ] struct_pa_mainloop_api._fields_ = [ ('_opaque_struct', c_int) ] pa_mainloop_api = struct_pa_mainloop_api # /usr/include/pulse/mainloop-api.h:51 enum_pa_io_event_flags = c_int PA_IO_EVENT_NULL = 0 PA_IO_EVENT_INPUT = 1 PA_IO_EVENT_OUTPUT = 2 PA_IO_EVENT_HANGUP = 4 PA_IO_EVENT_ERROR = 8 pa_io_event_flags_t = enum_pa_io_event_flags # /usr/include/pulse/mainloop-api.h:60 class struct_pa_io_event(Structure): __slots__ = [ ] struct_pa_io_event._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_io_event(Structure): __slots__ = [ ] struct_pa_io_event._fields_ = [ ('_opaque_struct', c_int) ] pa_io_event = struct_pa_io_event # /usr/include/pulse/mainloop-api.h:63 pa_io_event_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_io_event), c_int, pa_io_event_flags_t, POINTER(None)) # /usr/include/pulse/mainloop-api.h:65 pa_io_event_destroy_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_io_event), POINTER(None)) # /usr/include/pulse/mainloop-api.h:67 class struct_pa_time_event(Structure): __slots__ = [ ] struct_pa_time_event._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_time_event(Structure): __slots__ = [ ] struct_pa_time_event._fields_ = [ ('_opaque_struct', c_int) ] pa_time_event = struct_pa_time_event # /usr/include/pulse/mainloop-api.h:70 class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] pa_time_event_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_time_event), POINTER(struct_timeval), POINTER(None)) # /usr/include/pulse/mainloop-api.h:72 pa_time_event_destroy_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_time_event), POINTER(None)) # /usr/include/pulse/mainloop-api.h:74 class struct_pa_defer_event(Structure): __slots__ = [ ] struct_pa_defer_event._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_defer_event(Structure): __slots__ = [ ] struct_pa_defer_event._fields_ = [ ('_opaque_struct', c_int) ] pa_defer_event = struct_pa_defer_event # /usr/include/pulse/mainloop-api.h:77 pa_defer_event_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_defer_event), POINTER(None)) # /usr/include/pulse/mainloop-api.h:79 pa_defer_event_destroy_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_defer_event), POINTER(None)) # /usr/include/pulse/mainloop-api.h:81 # /usr/include/pulse/mainloop-api.h:120 pa_mainloop_api_once = _lib.pa_mainloop_api_once pa_mainloop_api_once.restype = None pa_mainloop_api_once.argtypes = [POINTER(pa_mainloop_api), CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(None)), POINTER(None)] PA_CHANNELS_MAX = 32 # /usr/include/pulse/sample.h:117 PA_RATE_MAX = 192000 # /usr/include/pulse/sample.h:120 enum_pa_sample_format = c_int PA_SAMPLE_U8 = 0 PA_SAMPLE_ALAW = 1 PA_SAMPLE_ULAW = 2 PA_SAMPLE_S16LE = 3 PA_SAMPLE_S16BE = 4 PA_SAMPLE_FLOAT32LE = 5 PA_SAMPLE_FLOAT32BE = 6 PA_SAMPLE_S32LE = 7 PA_SAMPLE_S32BE = 8 PA_SAMPLE_MAX = 9 PA_SAMPLE_INVALID = 10 pa_sample_format_t = enum_pa_sample_format # /usr/include/pulse/sample.h:135 class struct_pa_sample_spec(Structure): __slots__ = [ 'format', 'rate', 'channels', ] struct_pa_sample_spec._fields_ = [ ('format', pa_sample_format_t), ('rate', c_uint32), ('channels', c_uint8), ] pa_sample_spec = struct_pa_sample_spec # /usr/include/pulse/sample.h:173 pa_usec_t = c_uint64 # /usr/include/pulse/sample.h:176 # /usr/include/pulse/sample.h:179 pa_bytes_per_second = _lib.pa_bytes_per_second pa_bytes_per_second.restype = c_size_t pa_bytes_per_second.argtypes = [POINTER(pa_sample_spec)] # /usr/include/pulse/sample.h:182 pa_frame_size = _lib.pa_frame_size pa_frame_size.restype = c_size_t pa_frame_size.argtypes = [POINTER(pa_sample_spec)] # /usr/include/pulse/sample.h:185 pa_sample_size = _lib.pa_sample_size pa_sample_size.restype = c_size_t pa_sample_size.argtypes = [POINTER(pa_sample_spec)] # /usr/include/pulse/sample.h:188 pa_bytes_to_usec = _lib.pa_bytes_to_usec pa_bytes_to_usec.restype = pa_usec_t pa_bytes_to_usec.argtypes = [c_uint64, POINTER(pa_sample_spec)] # /usr/include/pulse/sample.h:191 pa_usec_to_bytes = _lib.pa_usec_to_bytes pa_usec_to_bytes.restype = c_size_t pa_usec_to_bytes.argtypes = [pa_usec_t, POINTER(pa_sample_spec)] # /usr/include/pulse/sample.h:194 pa_sample_spec_valid = _lib.pa_sample_spec_valid pa_sample_spec_valid.restype = c_int pa_sample_spec_valid.argtypes = [POINTER(pa_sample_spec)] # /usr/include/pulse/sample.h:197 pa_sample_spec_equal = _lib.pa_sample_spec_equal pa_sample_spec_equal.restype = c_int pa_sample_spec_equal.argtypes = [POINTER(pa_sample_spec), POINTER(pa_sample_spec)] # /usr/include/pulse/sample.h:200 pa_sample_format_to_string = _lib.pa_sample_format_to_string pa_sample_format_to_string.restype = c_char_p pa_sample_format_to_string.argtypes = [pa_sample_format_t] # /usr/include/pulse/sample.h:203 pa_parse_sample_format = _lib.pa_parse_sample_format pa_parse_sample_format.restype = pa_sample_format_t pa_parse_sample_format.argtypes = [c_char_p] PA_SAMPLE_SPEC_SNPRINT_MAX = 32 # /usr/include/pulse/sample.h:206 # /usr/include/pulse/sample.h:209 pa_sample_spec_snprint = _lib.pa_sample_spec_snprint pa_sample_spec_snprint.restype = c_char_p pa_sample_spec_snprint.argtypes = [c_char_p, c_size_t, POINTER(pa_sample_spec)] # /usr/include/pulse/sample.h:212 pa_bytes_snprint = _lib.pa_bytes_snprint pa_bytes_snprint.restype = c_char_p pa_bytes_snprint.argtypes = [c_char_p, c_size_t, c_uint] enum_pa_context_state = c_int PA_CONTEXT_UNCONNECTED = 0 PA_CONTEXT_CONNECTING = 1 PA_CONTEXT_AUTHORIZING = 2 PA_CONTEXT_SETTING_NAME = 3 PA_CONTEXT_READY = 4 PA_CONTEXT_FAILED = 5 PA_CONTEXT_TERMINATED = 6 pa_context_state_t = enum_pa_context_state # /usr/include/pulse/def.h:49 enum_pa_stream_state = c_int PA_STREAM_UNCONNECTED = 0 PA_STREAM_CREATING = 1 PA_STREAM_READY = 2 PA_STREAM_FAILED = 3 PA_STREAM_TERMINATED = 4 pa_stream_state_t = enum_pa_stream_state # /usr/include/pulse/def.h:58 enum_pa_operation_state = c_int PA_OPERATION_RUNNING = 0 PA_OPERATION_DONE = 1 PA_OPERATION_CANCELED = 2 pa_operation_state_t = enum_pa_operation_state # /usr/include/pulse/def.h:65 enum_pa_context_flags = c_int PA_CONTEXT_NOAUTOSPAWN = 1 pa_context_flags_t = enum_pa_context_flags # /usr/include/pulse/def.h:73 enum_pa_stream_direction = c_int PA_STREAM_NODIRECTION = 0 PA_STREAM_PLAYBACK = 1 PA_STREAM_RECORD = 2 PA_STREAM_UPLOAD = 3 pa_stream_direction_t = enum_pa_stream_direction # /usr/include/pulse/def.h:81 enum_pa_stream_flags = c_int PA_STREAM_START_CORKED = 1 PA_STREAM_INTERPOLATE_TIMING = 2 PA_STREAM_NOT_MONOTONOUS = 4 PA_STREAM_AUTO_TIMING_UPDATE = 8 PA_STREAM_NO_REMAP_CHANNELS = 16 PA_STREAM_NO_REMIX_CHANNELS = 32 PA_STREAM_FIX_FORMAT = 64 PA_STREAM_FIX_RATE = 128 PA_STREAM_FIX_CHANNELS = 256 PA_STREAM_DONT_MOVE = 512 PA_STREAM_VARIABLE_RATE = 1024 pa_stream_flags_t = enum_pa_stream_flags # /usr/include/pulse/def.h:212 class struct_pa_buffer_attr(Structure): __slots__ = [ 'maxlength', 'tlength', 'prebuf', 'minreq', 'fragsize', ] struct_pa_buffer_attr._fields_ = [ ('maxlength', c_uint32), ('tlength', c_uint32), ('prebuf', c_uint32), ('minreq', c_uint32), ('fragsize', c_uint32), ] pa_buffer_attr = struct_pa_buffer_attr # /usr/include/pulse/def.h:221 enum_pa_subscription_mask = c_int PA_SUBSCRIPTION_MASK_NULL = 0 PA_SUBSCRIPTION_MASK_SINK = 1 PA_SUBSCRIPTION_MASK_SOURCE = 2 PA_SUBSCRIPTION_MASK_SINK_INPUT = 4 PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT = 8 PA_SUBSCRIPTION_MASK_MODULE = 16 PA_SUBSCRIPTION_MASK_CLIENT = 32 PA_SUBSCRIPTION_MASK_SAMPLE_CACHE = 64 PA_SUBSCRIPTION_MASK_SERVER = 128 PA_SUBSCRIPTION_MASK_AUTOLOAD = 256 PA_SUBSCRIPTION_MASK_ALL = 511 pa_subscription_mask_t = enum_pa_subscription_mask # /usr/include/pulse/def.h:261 enum_pa_subscription_event_type = c_int PA_SUBSCRIPTION_EVENT_SINK = 0 PA_SUBSCRIPTION_EVENT_SOURCE = 1 PA_SUBSCRIPTION_EVENT_SINK_INPUT = 2 PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT = 3 PA_SUBSCRIPTION_EVENT_MODULE = 4 PA_SUBSCRIPTION_EVENT_CLIENT = 5 PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE = 6 PA_SUBSCRIPTION_EVENT_SERVER = 7 PA_SUBSCRIPTION_EVENT_AUTOLOAD = 8 PA_SUBSCRIPTION_EVENT_FACILITY_MASK = 15 PA_SUBSCRIPTION_EVENT_NEW = 0 PA_SUBSCRIPTION_EVENT_CHANGE = 16 PA_SUBSCRIPTION_EVENT_REMOVE = 32 PA_SUBSCRIPTION_EVENT_TYPE_MASK = 1632 pa_subscription_event_type_t = enum_pa_subscription_event_type # /usr/include/pulse/def.h:280 class struct_pa_timing_info(Structure): __slots__ = [ 'timestamp', 'synchronized_clocks', 'sink_usec', 'source_usec', 'transport_usec', 'playing', 'write_index_corrupt', 'write_index', 'read_index_corrupt', 'read_index', ] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ # XXX HACK struct timeval wasn't picked up by wraptypes #('_opaque_struct', c_int) ('tv_sec', c_long), ('tv_usec', c_long), ] struct_pa_timing_info._fields_ = [ ('timestamp', struct_timeval), ('synchronized_clocks', c_int), ('sink_usec', pa_usec_t), ('source_usec', pa_usec_t), ('transport_usec', pa_usec_t), ('playing', c_int), ('write_index_corrupt', c_int), ('write_index', c_int64), ('read_index_corrupt', c_int), ('read_index', c_int64), ] pa_timing_info = struct_pa_timing_info # /usr/include/pulse/def.h:347 class struct_pa_spawn_api(Structure): __slots__ = [ 'prefork', 'postfork', 'atfork', ] struct_pa_spawn_api._fields_ = [ ('prefork', POINTER(CFUNCTYPE(None))), ('postfork', POINTER(CFUNCTYPE(None))), ('atfork', POINTER(CFUNCTYPE(None))), ] pa_spawn_api = struct_pa_spawn_api # /usr/include/pulse/def.h:366 enum_pa_seek_mode = c_int PA_SEEK_RELATIVE = 0 PA_SEEK_ABSOLUTE = 1 PA_SEEK_RELATIVE_ON_READ = 2 PA_SEEK_RELATIVE_END = 3 pa_seek_mode_t = enum_pa_seek_mode # /usr/include/pulse/def.h:374 enum_pa_sink_flags = c_int PA_SINK_HW_VOLUME_CTRL = 1 PA_SINK_LATENCY = 2 PA_SINK_HARDWARE = 4 PA_SINK_NETWORK = 8 pa_sink_flags_t = enum_pa_sink_flags # /usr/include/pulse/def.h:382 enum_pa_source_flags = c_int PA_SOURCE_HW_VOLUME_CTRL = 1 PA_SOURCE_LATENCY = 2 PA_SOURCE_HARDWARE = 4 PA_SOURCE_NETWORK = 8 pa_source_flags_t = enum_pa_source_flags # /usr/include/pulse/def.h:390 pa_free_cb_t = CFUNCTYPE(None, POINTER(None)) # /usr/include/pulse/def.h:393 class struct_pa_operation(Structure): __slots__ = [ ] struct_pa_operation._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_operation(Structure): __slots__ = [ ] struct_pa_operation._fields_ = [ ('_opaque_struct', c_int) ] pa_operation = struct_pa_operation # /usr/include/pulse/operation.h:36 # /usr/include/pulse/operation.h:39 pa_operation_ref = _lib.pa_operation_ref pa_operation_ref.restype = POINTER(pa_operation) pa_operation_ref.argtypes = [POINTER(pa_operation)] # /usr/include/pulse/operation.h:42 pa_operation_unref = _lib.pa_operation_unref pa_operation_unref.restype = None pa_operation_unref.argtypes = [POINTER(pa_operation)] # /usr/include/pulse/operation.h:45 pa_operation_cancel = _lib.pa_operation_cancel pa_operation_cancel.restype = None pa_operation_cancel.argtypes = [POINTER(pa_operation)] # /usr/include/pulse/operation.h:48 pa_operation_get_state = _lib.pa_operation_get_state pa_operation_get_state.restype = pa_operation_state_t pa_operation_get_state.argtypes = [POINTER(pa_operation)] class struct_pa_context(Structure): __slots__ = [ ] struct_pa_context._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_context(Structure): __slots__ = [ ] struct_pa_context._fields_ = [ ('_opaque_struct', c_int) ] pa_context = struct_pa_context # /usr/include/pulse/context.h:160 pa_context_notify_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(None)) # /usr/include/pulse/context.h:163 pa_context_success_cb_t = CFUNCTYPE(None, POINTER(pa_context), c_int, POINTER(None)) # /usr/include/pulse/context.h:166 # /usr/include/pulse/context.h:170 pa_context_new = _lib.pa_context_new pa_context_new.restype = POINTER(pa_context) pa_context_new.argtypes = [POINTER(pa_mainloop_api), c_char_p] # /usr/include/pulse/context.h:173 pa_context_unref = _lib.pa_context_unref pa_context_unref.restype = None pa_context_unref.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:176 pa_context_ref = _lib.pa_context_ref pa_context_ref.restype = POINTER(pa_context) pa_context_ref.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:179 pa_context_set_state_callback = _lib.pa_context_set_state_callback pa_context_set_state_callback.restype = None pa_context_set_state_callback.argtypes = [POINTER(pa_context), pa_context_notify_cb_t, POINTER(None)] # /usr/include/pulse/context.h:182 pa_context_errno = _lib.pa_context_errno pa_context_errno.restype = c_int pa_context_errno.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:185 pa_context_is_pending = _lib.pa_context_is_pending pa_context_is_pending.restype = c_int pa_context_is_pending.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:188 pa_context_get_state = _lib.pa_context_get_state pa_context_get_state.restype = pa_context_state_t pa_context_get_state.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:197 pa_context_connect = _lib.pa_context_connect pa_context_connect.restype = c_int pa_context_connect.argtypes = [POINTER(pa_context), c_char_p, pa_context_flags_t, POINTER(pa_spawn_api)] # /usr/include/pulse/context.h:200 pa_context_disconnect = _lib.pa_context_disconnect pa_context_disconnect.restype = None pa_context_disconnect.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:203 pa_context_drain = _lib.pa_context_drain pa_context_drain.restype = POINTER(pa_operation) pa_context_drain.argtypes = [POINTER(pa_context), pa_context_notify_cb_t, POINTER(None)] # /usr/include/pulse/context.h:208 pa_context_exit_daemon = _lib.pa_context_exit_daemon pa_context_exit_daemon.restype = POINTER(pa_operation) pa_context_exit_daemon.argtypes = [POINTER(pa_context), pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/context.h:211 pa_context_set_default_sink = _lib.pa_context_set_default_sink pa_context_set_default_sink.restype = POINTER(pa_operation) pa_context_set_default_sink.argtypes = [POINTER(pa_context), c_char_p, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/context.h:214 pa_context_set_default_source = _lib.pa_context_set_default_source pa_context_set_default_source.restype = POINTER(pa_operation) pa_context_set_default_source.argtypes = [POINTER(pa_context), c_char_p, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/context.h:217 pa_context_is_local = _lib.pa_context_is_local pa_context_is_local.restype = c_int pa_context_is_local.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:220 pa_context_set_name = _lib.pa_context_set_name pa_context_set_name.restype = POINTER(pa_operation) pa_context_set_name.argtypes = [POINTER(pa_context), c_char_p, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/context.h:223 pa_context_get_server = _lib.pa_context_get_server pa_context_get_server.restype = c_char_p pa_context_get_server.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:226 pa_context_get_protocol_version = _lib.pa_context_get_protocol_version pa_context_get_protocol_version.restype = c_uint32 pa_context_get_protocol_version.argtypes = [POINTER(pa_context)] # /usr/include/pulse/context.h:229 pa_context_get_server_protocol_version = _lib.pa_context_get_server_protocol_version pa_context_get_server_protocol_version.restype = c_uint32 pa_context_get_server_protocol_version.argtypes = [POINTER(pa_context)] enum_pa_channel_position = c_int PA_CHANNEL_POSITION_INVALID = 0 PA_CHANNEL_POSITION_MONO = 0 PA_CHANNEL_POSITION_LEFT = 1 PA_CHANNEL_POSITION_RIGHT = 2 PA_CHANNEL_POSITION_CENTER = 3 PA_CHANNEL_POSITION_FRONT_LEFT = 0 PA_CHANNEL_POSITION_FRONT_RIGHT = 0 PA_CHANNEL_POSITION_FRONT_CENTER = 0 PA_CHANNEL_POSITION_REAR_CENTER = 1 PA_CHANNEL_POSITION_REAR_LEFT = 2 PA_CHANNEL_POSITION_REAR_RIGHT = 3 PA_CHANNEL_POSITION_LFE = 4 PA_CHANNEL_POSITION_SUBWOOFER = 0 PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER = 1 PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER = 2 PA_CHANNEL_POSITION_SIDE_LEFT = 3 PA_CHANNEL_POSITION_SIDE_RIGHT = 4 PA_CHANNEL_POSITION_AUX0 = 5 PA_CHANNEL_POSITION_AUX1 = 6 PA_CHANNEL_POSITION_AUX2 = 7 PA_CHANNEL_POSITION_AUX3 = 8 PA_CHANNEL_POSITION_AUX4 = 9 PA_CHANNEL_POSITION_AUX5 = 10 PA_CHANNEL_POSITION_AUX6 = 11 PA_CHANNEL_POSITION_AUX7 = 12 PA_CHANNEL_POSITION_AUX8 = 13 PA_CHANNEL_POSITION_AUX9 = 14 PA_CHANNEL_POSITION_AUX10 = 15 PA_CHANNEL_POSITION_AUX11 = 16 PA_CHANNEL_POSITION_AUX12 = 17 PA_CHANNEL_POSITION_AUX13 = 18 PA_CHANNEL_POSITION_AUX14 = 19 PA_CHANNEL_POSITION_AUX15 = 20 PA_CHANNEL_POSITION_AUX16 = 21 PA_CHANNEL_POSITION_AUX17 = 22 PA_CHANNEL_POSITION_AUX18 = 23 PA_CHANNEL_POSITION_AUX19 = 24 PA_CHANNEL_POSITION_AUX20 = 25 PA_CHANNEL_POSITION_AUX21 = 26 PA_CHANNEL_POSITION_AUX22 = 27 PA_CHANNEL_POSITION_AUX23 = 28 PA_CHANNEL_POSITION_AUX24 = 29 PA_CHANNEL_POSITION_AUX25 = 30 PA_CHANNEL_POSITION_AUX26 = 31 PA_CHANNEL_POSITION_AUX27 = 32 PA_CHANNEL_POSITION_AUX28 = 33 PA_CHANNEL_POSITION_AUX29 = 34 PA_CHANNEL_POSITION_AUX30 = 35 PA_CHANNEL_POSITION_AUX31 = 36 PA_CHANNEL_POSITION_TOP_CENTER = 37 PA_CHANNEL_POSITION_TOP_FRONT_LEFT = 38 PA_CHANNEL_POSITION_TOP_FRONT_RIGHT = 39 PA_CHANNEL_POSITION_TOP_FRONT_CENTER = 40 PA_CHANNEL_POSITION_TOP_REAR_LEFT = 41 PA_CHANNEL_POSITION_TOP_REAR_RIGHT = 42 PA_CHANNEL_POSITION_TOP_REAR_CENTER = 43 PA_CHANNEL_POSITION_MAX = 44 pa_channel_position_t = enum_pa_channel_position # /usr/include/pulse/channelmap.h:140 enum_pa_channel_map_def = c_int PA_CHANNEL_MAP_AIFF = 0 PA_CHANNEL_MAP_ALSA = 1 PA_CHANNEL_MAP_AUX = 2 PA_CHANNEL_MAP_WAVEEX = 3 PA_CHANNEL_MAP_OSS = 4 PA_CHANNEL_MAP_DEFAULT = 0 pa_channel_map_def_t = enum_pa_channel_map_def # /usr/include/pulse/channelmap.h:151 class struct_pa_channel_map(Structure): __slots__ = [ 'channels', 'map', ] struct_pa_channel_map._fields_ = [ ('channels', c_uint8), ('map', pa_channel_position_t * 32), ] pa_channel_map = struct_pa_channel_map # /usr/include/pulse/channelmap.h:159 # /usr/include/pulse/channelmap.h:162 pa_channel_map_init = _lib.pa_channel_map_init pa_channel_map_init.restype = POINTER(pa_channel_map) pa_channel_map_init.argtypes = [POINTER(pa_channel_map)] # /usr/include/pulse/channelmap.h:165 pa_channel_map_init_mono = _lib.pa_channel_map_init_mono pa_channel_map_init_mono.restype = POINTER(pa_channel_map) pa_channel_map_init_mono.argtypes = [POINTER(pa_channel_map)] # /usr/include/pulse/channelmap.h:168 pa_channel_map_init_stereo = _lib.pa_channel_map_init_stereo pa_channel_map_init_stereo.restype = POINTER(pa_channel_map) pa_channel_map_init_stereo.argtypes = [POINTER(pa_channel_map)] # /usr/include/pulse/channelmap.h:172 pa_channel_map_init_auto = _lib.pa_channel_map_init_auto pa_channel_map_init_auto.restype = POINTER(pa_channel_map) pa_channel_map_init_auto.argtypes = [POINTER(pa_channel_map), c_uint, pa_channel_map_def_t] # /usr/include/pulse/channelmap.h:175 pa_channel_position_to_string = _lib.pa_channel_position_to_string pa_channel_position_to_string.restype = c_char_p pa_channel_position_to_string.argtypes = [pa_channel_position_t] # /usr/include/pulse/channelmap.h:178 pa_channel_position_to_pretty_string = _lib.pa_channel_position_to_pretty_string pa_channel_position_to_pretty_string.restype = c_char_p pa_channel_position_to_pretty_string.argtypes = [pa_channel_position_t] PA_CHANNEL_MAP_SNPRINT_MAX = 336 # /usr/include/pulse/channelmap.h:181 # /usr/include/pulse/channelmap.h:184 pa_channel_map_snprint = _lib.pa_channel_map_snprint pa_channel_map_snprint.restype = c_char_p pa_channel_map_snprint.argtypes = [c_char_p, c_size_t, POINTER(pa_channel_map)] # /usr/include/pulse/channelmap.h:187 pa_channel_map_parse = _lib.pa_channel_map_parse pa_channel_map_parse.restype = POINTER(pa_channel_map) pa_channel_map_parse.argtypes = [POINTER(pa_channel_map), c_char_p] # /usr/include/pulse/channelmap.h:190 pa_channel_map_equal = _lib.pa_channel_map_equal pa_channel_map_equal.restype = c_int pa_channel_map_equal.argtypes = [POINTER(pa_channel_map), POINTER(pa_channel_map)] # /usr/include/pulse/channelmap.h:193 pa_channel_map_valid = _lib.pa_channel_map_valid pa_channel_map_valid.restype = c_int pa_channel_map_valid.argtypes = [POINTER(pa_channel_map)] pa_volume_t = c_uint32 # /usr/include/pulse/volume.h:101 PA_VOLUME_NORM = 65536 # /usr/include/pulse/volume.h:104 PA_VOLUME_MUTED = 0 # /usr/include/pulse/volume.h:107 class struct_pa_cvolume(Structure): __slots__ = [ 'channels', 'values', ] struct_pa_cvolume._fields_ = [ ('channels', c_uint8), ('values', pa_volume_t * 32), ] pa_cvolume = struct_pa_cvolume # /usr/include/pulse/volume.h:113 # /usr/include/pulse/volume.h:116 pa_cvolume_equal = _lib.pa_cvolume_equal pa_cvolume_equal.restype = c_int pa_cvolume_equal.argtypes = [POINTER(pa_cvolume), POINTER(pa_cvolume)] # /usr/include/pulse/volume.h:125 pa_cvolume_set = _lib.pa_cvolume_set pa_cvolume_set.restype = POINTER(pa_cvolume) pa_cvolume_set.argtypes = [POINTER(pa_cvolume), c_uint, pa_volume_t] PA_CVOLUME_SNPRINT_MAX = 64 # /usr/include/pulse/volume.h:128 # /usr/include/pulse/volume.h:131 pa_cvolume_snprint = _lib.pa_cvolume_snprint pa_cvolume_snprint.restype = c_char_p pa_cvolume_snprint.argtypes = [c_char_p, c_size_t, POINTER(pa_cvolume)] # /usr/include/pulse/volume.h:134 pa_cvolume_avg = _lib.pa_cvolume_avg pa_cvolume_avg.restype = pa_volume_t pa_cvolume_avg.argtypes = [POINTER(pa_cvolume)] # /usr/include/pulse/volume.h:137 pa_cvolume_valid = _lib.pa_cvolume_valid pa_cvolume_valid.restype = c_int pa_cvolume_valid.argtypes = [POINTER(pa_cvolume)] # /usr/include/pulse/volume.h:140 pa_cvolume_channels_equal_to = _lib.pa_cvolume_channels_equal_to pa_cvolume_channels_equal_to.restype = c_int pa_cvolume_channels_equal_to.argtypes = [POINTER(pa_cvolume), pa_volume_t] # /usr/include/pulse/volume.h:149 pa_sw_volume_multiply = _lib.pa_sw_volume_multiply pa_sw_volume_multiply.restype = pa_volume_t pa_sw_volume_multiply.argtypes = [pa_volume_t, pa_volume_t] # /usr/include/pulse/volume.h:152 pa_sw_cvolume_multiply = _lib.pa_sw_cvolume_multiply pa_sw_cvolume_multiply.restype = POINTER(pa_cvolume) pa_sw_cvolume_multiply.argtypes = [POINTER(pa_cvolume), POINTER(pa_cvolume), POINTER(pa_cvolume)] # /usr/include/pulse/volume.h:155 pa_sw_volume_from_dB = _lib.pa_sw_volume_from_dB pa_sw_volume_from_dB.restype = pa_volume_t pa_sw_volume_from_dB.argtypes = [c_double] # /usr/include/pulse/volume.h:158 pa_sw_volume_to_dB = _lib.pa_sw_volume_to_dB pa_sw_volume_to_dB.restype = c_double pa_sw_volume_to_dB.argtypes = [pa_volume_t] # /usr/include/pulse/volume.h:161 pa_sw_volume_from_linear = _lib.pa_sw_volume_from_linear pa_sw_volume_from_linear.restype = pa_volume_t pa_sw_volume_from_linear.argtypes = [c_double] # /usr/include/pulse/volume.h:164 pa_sw_volume_to_linear = _lib.pa_sw_volume_to_linear pa_sw_volume_to_linear.restype = c_double pa_sw_volume_to_linear.argtypes = [pa_volume_t] PA_DECIBEL_MININFTY = -200 # /usr/include/pulse/volume.h:170 class struct_pa_stream(Structure): __slots__ = [ ] struct_pa_stream._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_stream(Structure): __slots__ = [ ] struct_pa_stream._fields_ = [ ('_opaque_struct', c_int) ] pa_stream = struct_pa_stream # /usr/include/pulse/stream.h:268 pa_stream_success_cb_t = CFUNCTYPE(None, POINTER(pa_stream), c_int, POINTER(None)) # /usr/include/pulse/stream.h:271 pa_stream_request_cb_t = CFUNCTYPE(None, POINTER(pa_stream), c_size_t, POINTER(None)) # /usr/include/pulse/stream.h:274 pa_stream_notify_cb_t = CFUNCTYPE(None, POINTER(pa_stream), POINTER(None)) # /usr/include/pulse/stream.h:277 # /usr/include/pulse/stream.h:280 pa_stream_new = _lib.pa_stream_new pa_stream_new.restype = POINTER(pa_stream) pa_stream_new.argtypes = [POINTER(pa_context), c_char_p, POINTER(pa_sample_spec), POINTER(pa_channel_map)] # /usr/include/pulse/stream.h:287 pa_stream_unref = _lib.pa_stream_unref pa_stream_unref.restype = None pa_stream_unref.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:290 pa_stream_ref = _lib.pa_stream_ref pa_stream_ref.restype = POINTER(pa_stream) pa_stream_ref.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:293 pa_stream_get_state = _lib.pa_stream_get_state pa_stream_get_state.restype = pa_stream_state_t pa_stream_get_state.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:296 pa_stream_get_context = _lib.pa_stream_get_context pa_stream_get_context.restype = POINTER(pa_context) pa_stream_get_context.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:302 pa_stream_get_index = _lib.pa_stream_get_index pa_stream_get_index.restype = c_uint32 pa_stream_get_index.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:312 pa_stream_get_device_index = _lib.pa_stream_get_device_index pa_stream_get_device_index.restype = c_uint32 pa_stream_get_device_index.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:322 pa_stream_get_device_name = _lib.pa_stream_get_device_name pa_stream_get_device_name.restype = c_char_p pa_stream_get_device_name.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:328 pa_stream_is_suspended = _lib.pa_stream_is_suspended pa_stream_is_suspended.restype = c_int pa_stream_is_suspended.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:331 pa_stream_connect_playback = _lib.pa_stream_connect_playback pa_stream_connect_playback.restype = c_int pa_stream_connect_playback.argtypes = [POINTER(pa_stream), c_char_p, POINTER(pa_buffer_attr), pa_stream_flags_t, POINTER(pa_cvolume), POINTER(pa_stream)] # /usr/include/pulse/stream.h:340 pa_stream_connect_record = _lib.pa_stream_connect_record pa_stream_connect_record.restype = c_int pa_stream_connect_record.argtypes = [POINTER(pa_stream), c_char_p, POINTER(pa_buffer_attr), pa_stream_flags_t] # /usr/include/pulse/stream.h:347 pa_stream_disconnect = _lib.pa_stream_disconnect pa_stream_disconnect.restype = c_int pa_stream_disconnect.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:356 pa_stream_write = _lib.pa_stream_write pa_stream_write.restype = c_int pa_stream_write.argtypes = [POINTER(pa_stream), POINTER(None), c_size_t, pa_free_cb_t, c_int64, pa_seek_mode_t] # /usr/include/pulse/stream.h:369 pa_stream_peek = _lib.pa_stream_peek pa_stream_peek.restype = c_int pa_stream_peek.argtypes = [POINTER(pa_stream), POINTER(POINTER(None)), POINTER(c_size_t)] # /usr/include/pulse/stream.h:376 pa_stream_drop = _lib.pa_stream_drop pa_stream_drop.restype = c_int pa_stream_drop.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:379 pa_stream_writable_size = _lib.pa_stream_writable_size pa_stream_writable_size.restype = c_size_t pa_stream_writable_size.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:382 pa_stream_readable_size = _lib.pa_stream_readable_size pa_stream_readable_size.restype = c_size_t pa_stream_readable_size.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:385 pa_stream_drain = _lib.pa_stream_drain pa_stream_drain.restype = POINTER(pa_operation) pa_stream_drain.argtypes = [POINTER(pa_stream), pa_stream_success_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:391 pa_stream_update_timing_info = _lib.pa_stream_update_timing_info pa_stream_update_timing_info.restype = POINTER(pa_operation) pa_stream_update_timing_info.argtypes = [POINTER(pa_stream), pa_stream_success_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:394 pa_stream_set_state_callback = _lib.pa_stream_set_state_callback pa_stream_set_state_callback.restype = None pa_stream_set_state_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:398 pa_stream_set_write_callback = _lib.pa_stream_set_write_callback pa_stream_set_write_callback.restype = None pa_stream_set_write_callback.argtypes = [POINTER(pa_stream), pa_stream_request_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:402 pa_stream_set_read_callback = _lib.pa_stream_set_read_callback pa_stream_set_read_callback.restype = None pa_stream_set_read_callback.argtypes = [POINTER(pa_stream), pa_stream_request_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:405 pa_stream_set_overflow_callback = _lib.pa_stream_set_overflow_callback pa_stream_set_overflow_callback.restype = None pa_stream_set_overflow_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:408 pa_stream_set_underflow_callback = _lib.pa_stream_set_underflow_callback pa_stream_set_underflow_callback.restype = None pa_stream_set_underflow_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:413 pa_stream_set_latency_update_callback = _lib.pa_stream_set_latency_update_callback pa_stream_set_latency_update_callback.restype = None pa_stream_set_latency_update_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:420 pa_stream_set_moved_callback = _lib.pa_stream_set_moved_callback pa_stream_set_moved_callback.restype = None pa_stream_set_moved_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:430 pa_stream_set_suspended_callback = _lib.pa_stream_set_suspended_callback pa_stream_set_suspended_callback.restype = None pa_stream_set_suspended_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:433 pa_stream_cork = _lib.pa_stream_cork pa_stream_cork.restype = POINTER(pa_operation) pa_stream_cork.argtypes = [POINTER(pa_stream), c_int, pa_stream_success_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:438 pa_stream_flush = _lib.pa_stream_flush pa_stream_flush.restype = POINTER(pa_operation) pa_stream_flush.argtypes = [POINTER(pa_stream), pa_stream_success_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:442 pa_stream_prebuf = _lib.pa_stream_prebuf pa_stream_prebuf.restype = POINTER(pa_operation) pa_stream_prebuf.argtypes = [POINTER(pa_stream), pa_stream_success_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:447 pa_stream_trigger = _lib.pa_stream_trigger pa_stream_trigger.restype = POINTER(pa_operation) pa_stream_trigger.argtypes = [POINTER(pa_stream), pa_stream_success_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:450 pa_stream_set_name = _lib.pa_stream_set_name pa_stream_set_name.restype = POINTER(pa_operation) pa_stream_set_name.argtypes = [POINTER(pa_stream), c_char_p, pa_stream_success_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:467 pa_stream_get_time = _lib.pa_stream_get_time pa_stream_get_time.restype = c_int pa_stream_get_time.argtypes = [POINTER(pa_stream), POINTER(pa_usec_t)] # /usr/include/pulse/stream.h:473 pa_stream_get_latency = _lib.pa_stream_get_latency pa_stream_get_latency.restype = c_int pa_stream_get_latency.argtypes = [POINTER(pa_stream), POINTER(pa_usec_t), POINTER(c_int)] # /usr/include/pulse/stream.h:485 pa_stream_get_timing_info = _lib.pa_stream_get_timing_info pa_stream_get_timing_info.restype = POINTER(pa_timing_info) pa_stream_get_timing_info.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:488 pa_stream_get_sample_spec = _lib.pa_stream_get_sample_spec pa_stream_get_sample_spec.restype = POINTER(pa_sample_spec) pa_stream_get_sample_spec.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:491 pa_stream_get_channel_map = _lib.pa_stream_get_channel_map pa_stream_get_channel_map.restype = POINTER(pa_channel_map) pa_stream_get_channel_map.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:496 pa_stream_get_buffer_attr = _lib.pa_stream_get_buffer_attr pa_stream_get_buffer_attr.restype = POINTER(pa_buffer_attr) pa_stream_get_buffer_attr.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/stream.h:504 pa_stream_set_buffer_attr = _lib.pa_stream_set_buffer_attr pa_stream_set_buffer_attr.restype = POINTER(pa_operation) pa_stream_set_buffer_attr.argtypes = [POINTER(pa_stream), POINTER(pa_buffer_attr), pa_stream_success_cb_t, POINTER(None)] # /usr/include/pulse/stream.h:511 pa_stream_update_sample_rate = _lib.pa_stream_update_sample_rate pa_stream_update_sample_rate.restype = POINTER(pa_operation) pa_stream_update_sample_rate.argtypes = [POINTER(pa_stream), c_uint32, pa_stream_success_cb_t, POINTER(None)] class struct_pa_sink_info(Structure): __slots__ = [ 'name', 'index', 'description', 'sample_spec', 'channel_map', 'owner_module', 'volume', 'mute', 'monitor_source', 'monitor_source_name', 'latency', 'driver', 'flags', ] struct_pa_sink_info._fields_ = [ ('name', c_char_p), ('index', c_uint32), ('description', c_char_p), ('sample_spec', pa_sample_spec), ('channel_map', pa_channel_map), ('owner_module', c_uint32), ('volume', pa_cvolume), ('mute', c_int), ('monitor_source', c_uint32), ('monitor_source_name', c_char_p), ('latency', pa_usec_t), ('driver', c_char_p), ('flags', pa_sink_flags_t), ] pa_sink_info = struct_pa_sink_info # /usr/include/pulse/introspect.h:224 pa_sink_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_sink_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:227 # /usr/include/pulse/introspect.h:230 pa_context_get_sink_info_by_name = _lib.pa_context_get_sink_info_by_name pa_context_get_sink_info_by_name.restype = POINTER(pa_operation) pa_context_get_sink_info_by_name.argtypes = [POINTER(pa_context), c_char_p, pa_sink_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:233 pa_context_get_sink_info_by_index = _lib.pa_context_get_sink_info_by_index pa_context_get_sink_info_by_index.restype = POINTER(pa_operation) pa_context_get_sink_info_by_index.argtypes = [POINTER(pa_context), c_uint32, pa_sink_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:236 pa_context_get_sink_info_list = _lib.pa_context_get_sink_info_list pa_context_get_sink_info_list.restype = POINTER(pa_operation) pa_context_get_sink_info_list.argtypes = [POINTER(pa_context), pa_sink_info_cb_t, POINTER(None)] class struct_pa_source_info(Structure): __slots__ = [ 'name', 'index', 'description', 'sample_spec', 'channel_map', 'owner_module', 'volume', 'mute', 'monitor_of_sink', 'monitor_of_sink_name', 'latency', 'driver', 'flags', ] struct_pa_source_info._fields_ = [ ('name', c_char_p), ('index', c_uint32), ('description', c_char_p), ('sample_spec', pa_sample_spec), ('channel_map', pa_channel_map), ('owner_module', c_uint32), ('volume', pa_cvolume), ('mute', c_int), ('monitor_of_sink', c_uint32), ('monitor_of_sink_name', c_char_p), ('latency', pa_usec_t), ('driver', c_char_p), ('flags', pa_source_flags_t), ] pa_source_info = struct_pa_source_info # /usr/include/pulse/introspect.h:253 pa_source_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_source_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:256 # /usr/include/pulse/introspect.h:259 pa_context_get_source_info_by_name = _lib.pa_context_get_source_info_by_name pa_context_get_source_info_by_name.restype = POINTER(pa_operation) pa_context_get_source_info_by_name.argtypes = [POINTER(pa_context), c_char_p, pa_source_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:262 pa_context_get_source_info_by_index = _lib.pa_context_get_source_info_by_index pa_context_get_source_info_by_index.restype = POINTER(pa_operation) pa_context_get_source_info_by_index.argtypes = [POINTER(pa_context), c_uint32, pa_source_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:265 pa_context_get_source_info_list = _lib.pa_context_get_source_info_list pa_context_get_source_info_list.restype = POINTER(pa_operation) pa_context_get_source_info_list.argtypes = [POINTER(pa_context), pa_source_info_cb_t, POINTER(None)] class struct_pa_server_info(Structure): __slots__ = [ 'user_name', 'host_name', 'server_version', 'server_name', 'sample_spec', 'default_sink_name', 'default_source_name', 'cookie', ] struct_pa_server_info._fields_ = [ ('user_name', c_char_p), ('host_name', c_char_p), ('server_version', c_char_p), ('server_name', c_char_p), ('sample_spec', pa_sample_spec), ('default_sink_name', c_char_p), ('default_source_name', c_char_p), ('cookie', c_uint32), ] pa_server_info = struct_pa_server_info # /usr/include/pulse/introspect.h:277 pa_server_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_server_info), POINTER(None)) # /usr/include/pulse/introspect.h:280 # /usr/include/pulse/introspect.h:283 pa_context_get_server_info = _lib.pa_context_get_server_info pa_context_get_server_info.restype = POINTER(pa_operation) pa_context_get_server_info.argtypes = [POINTER(pa_context), pa_server_info_cb_t, POINTER(None)] class struct_pa_module_info(Structure): __slots__ = [ 'index', 'name', 'argument', 'n_used', 'auto_unload', ] struct_pa_module_info._fields_ = [ ('index', c_uint32), ('name', c_char_p), ('argument', c_char_p), ('n_used', c_uint32), ('auto_unload', c_int), ] pa_module_info = struct_pa_module_info # /usr/include/pulse/introspect.h:292 pa_module_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_module_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:295 # /usr/include/pulse/introspect.h:298 pa_context_get_module_info = _lib.pa_context_get_module_info pa_context_get_module_info.restype = POINTER(pa_operation) pa_context_get_module_info.argtypes = [POINTER(pa_context), c_uint32, pa_module_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:301 pa_context_get_module_info_list = _lib.pa_context_get_module_info_list pa_context_get_module_info_list.restype = POINTER(pa_operation) pa_context_get_module_info_list.argtypes = [POINTER(pa_context), pa_module_info_cb_t, POINTER(None)] class struct_pa_client_info(Structure): __slots__ = [ 'index', 'name', 'owner_module', 'driver', ] struct_pa_client_info._fields_ = [ ('index', c_uint32), ('name', c_char_p), ('owner_module', c_uint32), ('driver', c_char_p), ] pa_client_info = struct_pa_client_info # /usr/include/pulse/introspect.h:309 pa_client_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_client_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:312 # /usr/include/pulse/introspect.h:315 pa_context_get_client_info = _lib.pa_context_get_client_info pa_context_get_client_info.restype = POINTER(pa_operation) pa_context_get_client_info.argtypes = [POINTER(pa_context), c_uint32, pa_client_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:318 pa_context_get_client_info_list = _lib.pa_context_get_client_info_list pa_context_get_client_info_list.restype = POINTER(pa_operation) pa_context_get_client_info_list.argtypes = [POINTER(pa_context), pa_client_info_cb_t, POINTER(None)] class struct_pa_sink_input_info(Structure): __slots__ = [ 'index', 'name', 'owner_module', 'client', 'sink', 'sample_spec', 'channel_map', 'volume', 'buffer_usec', 'sink_usec', 'resample_method', 'driver', 'mute', ] struct_pa_sink_input_info._fields_ = [ ('index', c_uint32), ('name', c_char_p), ('owner_module', c_uint32), ('client', c_uint32), ('sink', c_uint32), ('sample_spec', pa_sample_spec), ('channel_map', pa_channel_map), ('volume', pa_cvolume), ('buffer_usec', pa_usec_t), ('sink_usec', pa_usec_t), ('resample_method', c_char_p), ('driver', c_char_p), ('mute', c_int), ] pa_sink_input_info = struct_pa_sink_input_info # /usr/include/pulse/introspect.h:335 pa_sink_input_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_sink_input_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:338 # /usr/include/pulse/introspect.h:341 pa_context_get_sink_input_info = _lib.pa_context_get_sink_input_info pa_context_get_sink_input_info.restype = POINTER(pa_operation) pa_context_get_sink_input_info.argtypes = [POINTER(pa_context), c_uint32, pa_sink_input_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:344 pa_context_get_sink_input_info_list = _lib.pa_context_get_sink_input_info_list pa_context_get_sink_input_info_list.restype = POINTER(pa_operation) pa_context_get_sink_input_info_list.argtypes = [POINTER(pa_context), pa_sink_input_info_cb_t, POINTER(None)] class struct_pa_source_output_info(Structure): __slots__ = [ 'index', 'name', 'owner_module', 'client', 'source', 'sample_spec', 'channel_map', 'buffer_usec', 'source_usec', 'resample_method', 'driver', ] struct_pa_source_output_info._fields_ = [ ('index', c_uint32), ('name', c_char_p), ('owner_module', c_uint32), ('client', c_uint32), ('source', c_uint32), ('sample_spec', pa_sample_spec), ('channel_map', pa_channel_map), ('buffer_usec', pa_usec_t), ('source_usec', pa_usec_t), ('resample_method', c_char_p), ('driver', c_char_p), ] pa_source_output_info = struct_pa_source_output_info # /usr/include/pulse/introspect.h:359 pa_source_output_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_source_output_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:362 # /usr/include/pulse/introspect.h:365 pa_context_get_source_output_info = _lib.pa_context_get_source_output_info pa_context_get_source_output_info.restype = POINTER(pa_operation) pa_context_get_source_output_info.argtypes = [POINTER(pa_context), c_uint32, pa_source_output_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:368 pa_context_get_source_output_info_list = _lib.pa_context_get_source_output_info_list pa_context_get_source_output_info_list.restype = POINTER(pa_operation) pa_context_get_source_output_info_list.argtypes = [POINTER(pa_context), pa_source_output_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:371 pa_context_set_sink_volume_by_index = _lib.pa_context_set_sink_volume_by_index pa_context_set_sink_volume_by_index.restype = POINTER(pa_operation) pa_context_set_sink_volume_by_index.argtypes = [POINTER(pa_context), c_uint32, POINTER(pa_cvolume), pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:374 pa_context_set_sink_volume_by_name = _lib.pa_context_set_sink_volume_by_name pa_context_set_sink_volume_by_name.restype = POINTER(pa_operation) pa_context_set_sink_volume_by_name.argtypes = [POINTER(pa_context), c_char_p, POINTER(pa_cvolume), pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:377 pa_context_set_sink_mute_by_index = _lib.pa_context_set_sink_mute_by_index pa_context_set_sink_mute_by_index.restype = POINTER(pa_operation) pa_context_set_sink_mute_by_index.argtypes = [POINTER(pa_context), c_uint32, c_int, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:380 pa_context_set_sink_mute_by_name = _lib.pa_context_set_sink_mute_by_name pa_context_set_sink_mute_by_name.restype = POINTER(pa_operation) pa_context_set_sink_mute_by_name.argtypes = [POINTER(pa_context), c_char_p, c_int, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:383 pa_context_set_sink_input_volume = _lib.pa_context_set_sink_input_volume pa_context_set_sink_input_volume.restype = POINTER(pa_operation) pa_context_set_sink_input_volume.argtypes = [POINTER(pa_context), c_uint32, POINTER(pa_cvolume), pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:386 pa_context_set_sink_input_mute = _lib.pa_context_set_sink_input_mute pa_context_set_sink_input_mute.restype = POINTER(pa_operation) pa_context_set_sink_input_mute.argtypes = [POINTER(pa_context), c_uint32, c_int, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:389 pa_context_set_source_volume_by_index = _lib.pa_context_set_source_volume_by_index pa_context_set_source_volume_by_index.restype = POINTER(pa_operation) pa_context_set_source_volume_by_index.argtypes = [POINTER(pa_context), c_uint32, POINTER(pa_cvolume), pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:392 pa_context_set_source_volume_by_name = _lib.pa_context_set_source_volume_by_name pa_context_set_source_volume_by_name.restype = POINTER(pa_operation) pa_context_set_source_volume_by_name.argtypes = [POINTER(pa_context), c_char_p, POINTER(pa_cvolume), pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:395 pa_context_set_source_mute_by_index = _lib.pa_context_set_source_mute_by_index pa_context_set_source_mute_by_index.restype = POINTER(pa_operation) pa_context_set_source_mute_by_index.argtypes = [POINTER(pa_context), c_uint32, c_int, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:398 pa_context_set_source_mute_by_name = _lib.pa_context_set_source_mute_by_name pa_context_set_source_mute_by_name.restype = POINTER(pa_operation) pa_context_set_source_mute_by_name.argtypes = [POINTER(pa_context), c_char_p, c_int, pa_context_success_cb_t, POINTER(None)] class struct_pa_stat_info(Structure): __slots__ = [ 'memblock_total', 'memblock_total_size', 'memblock_allocated', 'memblock_allocated_size', 'scache_size', ] struct_pa_stat_info._fields_ = [ ('memblock_total', c_uint32), ('memblock_total_size', c_uint32), ('memblock_allocated', c_uint32), ('memblock_allocated_size', c_uint32), ('scache_size', c_uint32), ] pa_stat_info = struct_pa_stat_info # /usr/include/pulse/introspect.h:407 pa_stat_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_stat_info), POINTER(None)) # /usr/include/pulse/introspect.h:410 # /usr/include/pulse/introspect.h:413 pa_context_stat = _lib.pa_context_stat pa_context_stat.restype = POINTER(pa_operation) pa_context_stat.argtypes = [POINTER(pa_context), pa_stat_info_cb_t, POINTER(None)] class struct_pa_sample_info(Structure): __slots__ = [ 'index', 'name', 'volume', 'sample_spec', 'channel_map', 'duration', 'bytes', 'lazy', 'filename', ] struct_pa_sample_info._fields_ = [ ('index', c_uint32), ('name', c_char_p), ('volume', pa_cvolume), ('sample_spec', pa_sample_spec), ('channel_map', pa_channel_map), ('duration', pa_usec_t), ('bytes', c_uint32), ('lazy', c_int), ('filename', c_char_p), ] pa_sample_info = struct_pa_sample_info # /usr/include/pulse/introspect.h:426 pa_sample_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_sample_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:429 # /usr/include/pulse/introspect.h:432 pa_context_get_sample_info_by_name = _lib.pa_context_get_sample_info_by_name pa_context_get_sample_info_by_name.restype = POINTER(pa_operation) pa_context_get_sample_info_by_name.argtypes = [POINTER(pa_context), c_char_p, pa_sample_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:435 pa_context_get_sample_info_by_index = _lib.pa_context_get_sample_info_by_index pa_context_get_sample_info_by_index.restype = POINTER(pa_operation) pa_context_get_sample_info_by_index.argtypes = [POINTER(pa_context), c_uint32, pa_sample_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:438 pa_context_get_sample_info_list = _lib.pa_context_get_sample_info_list pa_context_get_sample_info_list.restype = POINTER(pa_operation) pa_context_get_sample_info_list.argtypes = [POINTER(pa_context), pa_sample_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:441 pa_context_kill_client = _lib.pa_context_kill_client pa_context_kill_client.restype = POINTER(pa_operation) pa_context_kill_client.argtypes = [POINTER(pa_context), c_uint32, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:444 pa_context_kill_sink_input = _lib.pa_context_kill_sink_input pa_context_kill_sink_input.restype = POINTER(pa_operation) pa_context_kill_sink_input.argtypes = [POINTER(pa_context), c_uint32, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:447 pa_context_kill_source_output = _lib.pa_context_kill_source_output pa_context_kill_source_output.restype = POINTER(pa_operation) pa_context_kill_source_output.argtypes = [POINTER(pa_context), c_uint32, pa_context_success_cb_t, POINTER(None)] pa_context_index_cb_t = CFUNCTYPE(None, POINTER(pa_context), c_uint32, POINTER(None)) # /usr/include/pulse/introspect.h:450 # /usr/include/pulse/introspect.h:453 pa_context_load_module = _lib.pa_context_load_module pa_context_load_module.restype = POINTER(pa_operation) pa_context_load_module.argtypes = [POINTER(pa_context), c_char_p, c_char_p, pa_context_index_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:456 pa_context_unload_module = _lib.pa_context_unload_module pa_context_unload_module.restype = POINTER(pa_operation) pa_context_unload_module.argtypes = [POINTER(pa_context), c_uint32, pa_context_success_cb_t, POINTER(None)] enum_pa_autoload_type = c_int PA_AUTOLOAD_SINK = 0 PA_AUTOLOAD_SOURCE = 1 pa_autoload_type_t = enum_pa_autoload_type # /usr/include/pulse/introspect.h:462 class struct_pa_autoload_info(Structure): __slots__ = [ 'index', 'name', 'type', 'module', 'argument', ] struct_pa_autoload_info._fields_ = [ ('index', c_uint32), ('name', c_char_p), ('type', pa_autoload_type_t), ('module', c_char_p), ('argument', c_char_p), ] pa_autoload_info = struct_pa_autoload_info # /usr/include/pulse/introspect.h:471 pa_autoload_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_autoload_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:474 # /usr/include/pulse/introspect.h:477 pa_context_get_autoload_info_by_name = _lib.pa_context_get_autoload_info_by_name pa_context_get_autoload_info_by_name.restype = POINTER(pa_operation) pa_context_get_autoload_info_by_name.argtypes = [POINTER(pa_context), c_char_p, pa_autoload_type_t, pa_autoload_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:480 pa_context_get_autoload_info_by_index = _lib.pa_context_get_autoload_info_by_index pa_context_get_autoload_info_by_index.restype = POINTER(pa_operation) pa_context_get_autoload_info_by_index.argtypes = [POINTER(pa_context), c_uint32, pa_autoload_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:483 pa_context_get_autoload_info_list = _lib.pa_context_get_autoload_info_list pa_context_get_autoload_info_list.restype = POINTER(pa_operation) pa_context_get_autoload_info_list.argtypes = [POINTER(pa_context), pa_autoload_info_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:486 pa_context_add_autoload = _lib.pa_context_add_autoload pa_context_add_autoload.restype = POINTER(pa_operation) pa_context_add_autoload.argtypes = [POINTER(pa_context), c_char_p, pa_autoload_type_t, c_char_p, c_char_p, pa_context_index_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:489 pa_context_remove_autoload_by_name = _lib.pa_context_remove_autoload_by_name pa_context_remove_autoload_by_name.restype = POINTER(pa_operation) pa_context_remove_autoload_by_name.argtypes = [POINTER(pa_context), c_char_p, pa_autoload_type_t, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:492 pa_context_remove_autoload_by_index = _lib.pa_context_remove_autoload_by_index pa_context_remove_autoload_by_index.restype = POINTER(pa_operation) pa_context_remove_autoload_by_index.argtypes = [POINTER(pa_context), c_uint32, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:495 pa_context_move_sink_input_by_name = _lib.pa_context_move_sink_input_by_name pa_context_move_sink_input_by_name.restype = POINTER(pa_operation) pa_context_move_sink_input_by_name.argtypes = [POINTER(pa_context), c_uint32, c_char_p, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:498 pa_context_move_sink_input_by_index = _lib.pa_context_move_sink_input_by_index pa_context_move_sink_input_by_index.restype = POINTER(pa_operation) pa_context_move_sink_input_by_index.argtypes = [POINTER(pa_context), c_uint32, c_uint32, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:501 pa_context_move_source_output_by_name = _lib.pa_context_move_source_output_by_name pa_context_move_source_output_by_name.restype = POINTER(pa_operation) pa_context_move_source_output_by_name.argtypes = [POINTER(pa_context), c_uint32, c_char_p, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:504 pa_context_move_source_output_by_index = _lib.pa_context_move_source_output_by_index pa_context_move_source_output_by_index.restype = POINTER(pa_operation) pa_context_move_source_output_by_index.argtypes = [POINTER(pa_context), c_uint32, c_uint32, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:507 pa_context_suspend_sink_by_name = _lib.pa_context_suspend_sink_by_name pa_context_suspend_sink_by_name.restype = POINTER(pa_operation) pa_context_suspend_sink_by_name.argtypes = [POINTER(pa_context), c_char_p, c_int, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:510 pa_context_suspend_sink_by_index = _lib.pa_context_suspend_sink_by_index pa_context_suspend_sink_by_index.restype = POINTER(pa_operation) pa_context_suspend_sink_by_index.argtypes = [POINTER(pa_context), c_uint32, c_int, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:513 pa_context_suspend_source_by_name = _lib.pa_context_suspend_source_by_name pa_context_suspend_source_by_name.restype = POINTER(pa_operation) pa_context_suspend_source_by_name.argtypes = [POINTER(pa_context), c_char_p, c_int, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/introspect.h:516 pa_context_suspend_source_by_index = _lib.pa_context_suspend_source_by_index pa_context_suspend_source_by_index.restype = POINTER(pa_operation) pa_context_suspend_source_by_index.argtypes = [POINTER(pa_context), c_uint32, c_int, pa_context_success_cb_t, POINTER(None)] pa_context_subscribe_cb_t = CFUNCTYPE(None, POINTER(pa_context), pa_subscription_event_type_t, c_uint32, POINTER(None)) # /usr/include/pulse/subscribe.h:54 # /usr/include/pulse/subscribe.h:57 pa_context_subscribe = _lib.pa_context_subscribe pa_context_subscribe.restype = POINTER(pa_operation) pa_context_subscribe.argtypes = [POINTER(pa_context), pa_subscription_mask_t, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/subscribe.h:60 pa_context_set_subscribe_callback = _lib.pa_context_set_subscribe_callback pa_context_set_subscribe_callback.restype = None pa_context_set_subscribe_callback.argtypes = [POINTER(pa_context), pa_context_subscribe_cb_t, POINTER(None)] # /usr/include/pulse/scache.h:83 pa_stream_connect_upload = _lib.pa_stream_connect_upload pa_stream_connect_upload.restype = c_int pa_stream_connect_upload.argtypes = [POINTER(pa_stream), c_size_t] # /usr/include/pulse/scache.h:87 pa_stream_finish_upload = _lib.pa_stream_finish_upload pa_stream_finish_upload.restype = c_int pa_stream_finish_upload.argtypes = [POINTER(pa_stream)] # /usr/include/pulse/scache.h:90 pa_context_play_sample = _lib.pa_context_play_sample pa_context_play_sample.restype = POINTER(pa_operation) pa_context_play_sample.argtypes = [POINTER(pa_context), c_char_p, c_char_p, pa_volume_t, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/scache.h:99 pa_context_remove_sample = _lib.pa_context_remove_sample pa_context_remove_sample.restype = POINTER(pa_operation) pa_context_remove_sample.argtypes = [POINTER(pa_context), c_char_p, pa_context_success_cb_t, POINTER(None)] # /usr/include/pulse/version.h:43 pa_get_library_version = _lib.pa_get_library_version pa_get_library_version.restype = c_char_p pa_get_library_version.argtypes = [] PA_API_VERSION = 11 # /usr/include/pulse/version.h:48 PA_PROTOCOL_VERSION = 12 # /usr/include/pulse/version.h:52 # /usr/include/pulse/error.h:37 pa_strerror = _lib.pa_strerror pa_strerror.restype = c_char_p pa_strerror.argtypes = [c_int] # /usr/include/pulse/xmalloc.h:40 pa_xmalloc = _lib.pa_xmalloc pa_xmalloc.restype = POINTER(c_void) pa_xmalloc.argtypes = [c_size_t] # /usr/include/pulse/xmalloc.h:43 pa_xmalloc0 = _lib.pa_xmalloc0 pa_xmalloc0.restype = POINTER(c_void) pa_xmalloc0.argtypes = [c_size_t] # /usr/include/pulse/xmalloc.h:46 pa_xrealloc = _lib.pa_xrealloc pa_xrealloc.restype = POINTER(c_void) pa_xrealloc.argtypes = [POINTER(None), c_size_t] # /usr/include/pulse/xmalloc.h:49 pa_xfree = _lib.pa_xfree pa_xfree.restype = None pa_xfree.argtypes = [POINTER(None)] # /usr/include/pulse/xmalloc.h:52 pa_xstrdup = _lib.pa_xstrdup pa_xstrdup.restype = c_char_p pa_xstrdup.argtypes = [c_char_p] # /usr/include/pulse/xmalloc.h:55 pa_xstrndup = _lib.pa_xstrndup pa_xstrndup.restype = c_char_p pa_xstrndup.argtypes = [c_char_p, c_size_t] # /usr/include/pulse/xmalloc.h:58 pa_xmemdup = _lib.pa_xmemdup pa_xmemdup.restype = POINTER(c_void) pa_xmemdup.argtypes = [POINTER(None), c_size_t] # /usr/include/pulse/utf8.h:37 pa_utf8_valid = _lib.pa_utf8_valid pa_utf8_valid.restype = c_char_p pa_utf8_valid.argtypes = [c_char_p] # /usr/include/pulse/utf8.h:40 pa_utf8_filter = _lib.pa_utf8_filter pa_utf8_filter.restype = c_char_p pa_utf8_filter.argtypes = [c_char_p] # /usr/include/pulse/utf8.h:43 pa_utf8_to_locale = _lib.pa_utf8_to_locale pa_utf8_to_locale.restype = c_char_p pa_utf8_to_locale.argtypes = [c_char_p] # /usr/include/pulse/utf8.h:46 pa_locale_to_utf8 = _lib.pa_locale_to_utf8 pa_locale_to_utf8.restype = c_char_p pa_locale_to_utf8.argtypes = [c_char_p] class struct_pa_threaded_mainloop(Structure): __slots__ = [ ] struct_pa_threaded_mainloop._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_threaded_mainloop(Structure): __slots__ = [ ] struct_pa_threaded_mainloop._fields_ = [ ('_opaque_struct', c_int) ] pa_threaded_mainloop = struct_pa_threaded_mainloop # /usr/include/pulse/thread-mainloop.h:242 # /usr/include/pulse/thread-mainloop.h:247 pa_threaded_mainloop_new = _lib.pa_threaded_mainloop_new pa_threaded_mainloop_new.restype = POINTER(pa_threaded_mainloop) pa_threaded_mainloop_new.argtypes = [] # /usr/include/pulse/thread-mainloop.h:252 pa_threaded_mainloop_free = _lib.pa_threaded_mainloop_free pa_threaded_mainloop_free.restype = None pa_threaded_mainloop_free.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:255 pa_threaded_mainloop_start = _lib.pa_threaded_mainloop_start pa_threaded_mainloop_start.restype = c_int pa_threaded_mainloop_start.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:259 pa_threaded_mainloop_stop = _lib.pa_threaded_mainloop_stop pa_threaded_mainloop_stop.restype = None pa_threaded_mainloop_stop.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:267 pa_threaded_mainloop_lock = _lib.pa_threaded_mainloop_lock pa_threaded_mainloop_lock.restype = None pa_threaded_mainloop_lock.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:270 pa_threaded_mainloop_unlock = _lib.pa_threaded_mainloop_unlock pa_threaded_mainloop_unlock.restype = None pa_threaded_mainloop_unlock.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:279 pa_threaded_mainloop_wait = _lib.pa_threaded_mainloop_wait pa_threaded_mainloop_wait.restype = None pa_threaded_mainloop_wait.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:286 pa_threaded_mainloop_signal = _lib.pa_threaded_mainloop_signal pa_threaded_mainloop_signal.restype = None pa_threaded_mainloop_signal.argtypes = [POINTER(pa_threaded_mainloop), c_int] # /usr/include/pulse/thread-mainloop.h:292 pa_threaded_mainloop_accept = _lib.pa_threaded_mainloop_accept pa_threaded_mainloop_accept.restype = None pa_threaded_mainloop_accept.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:295 pa_threaded_mainloop_get_retval = _lib.pa_threaded_mainloop_get_retval pa_threaded_mainloop_get_retval.restype = c_int pa_threaded_mainloop_get_retval.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:298 pa_threaded_mainloop_get_api = _lib.pa_threaded_mainloop_get_api pa_threaded_mainloop_get_api.restype = POINTER(pa_mainloop_api) pa_threaded_mainloop_get_api.argtypes = [POINTER(pa_threaded_mainloop)] # /usr/include/pulse/thread-mainloop.h:301 pa_threaded_mainloop_in_thread = _lib.pa_threaded_mainloop_in_thread pa_threaded_mainloop_in_thread.restype = c_int pa_threaded_mainloop_in_thread.argtypes = [POINTER(pa_threaded_mainloop)] class struct_pa_mainloop(Structure): __slots__ = [ ] struct_pa_mainloop._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_mainloop(Structure): __slots__ = [ ] struct_pa_mainloop._fields_ = [ ('_opaque_struct', c_int) ] pa_mainloop = struct_pa_mainloop # /usr/include/pulse/mainloop.h:79 # /usr/include/pulse/mainloop.h:82 pa_mainloop_new = _lib.pa_mainloop_new pa_mainloop_new.restype = POINTER(pa_mainloop) pa_mainloop_new.argtypes = [] # /usr/include/pulse/mainloop.h:85 pa_mainloop_free = _lib.pa_mainloop_free pa_mainloop_free.restype = None pa_mainloop_free.argtypes = [POINTER(pa_mainloop)] # /usr/include/pulse/mainloop.h:90 pa_mainloop_prepare = _lib.pa_mainloop_prepare pa_mainloop_prepare.restype = c_int pa_mainloop_prepare.argtypes = [POINTER(pa_mainloop), c_int] # /usr/include/pulse/mainloop.h:93 pa_mainloop_poll = _lib.pa_mainloop_poll pa_mainloop_poll.restype = c_int pa_mainloop_poll.argtypes = [POINTER(pa_mainloop)] # /usr/include/pulse/mainloop.h:97 pa_mainloop_dispatch = _lib.pa_mainloop_dispatch pa_mainloop_dispatch.restype = c_int pa_mainloop_dispatch.argtypes = [POINTER(pa_mainloop)] # /usr/include/pulse/mainloop.h:100 pa_mainloop_get_retval = _lib.pa_mainloop_get_retval pa_mainloop_get_retval.restype = c_int pa_mainloop_get_retval.argtypes = [POINTER(pa_mainloop)] # /usr/include/pulse/mainloop.h:108 pa_mainloop_iterate = _lib.pa_mainloop_iterate pa_mainloop_iterate.restype = c_int pa_mainloop_iterate.argtypes = [POINTER(pa_mainloop), c_int, POINTER(c_int)] # /usr/include/pulse/mainloop.h:111 pa_mainloop_run = _lib.pa_mainloop_run pa_mainloop_run.restype = c_int pa_mainloop_run.argtypes = [POINTER(pa_mainloop), POINTER(c_int)] # /usr/include/pulse/mainloop.h:114 pa_mainloop_get_api = _lib.pa_mainloop_get_api pa_mainloop_get_api.restype = POINTER(pa_mainloop_api) pa_mainloop_get_api.argtypes = [POINTER(pa_mainloop)] # /usr/include/pulse/mainloop.h:117 pa_mainloop_quit = _lib.pa_mainloop_quit pa_mainloop_quit.restype = None pa_mainloop_quit.argtypes = [POINTER(pa_mainloop), c_int] # /usr/include/pulse/mainloop.h:120 pa_mainloop_wakeup = _lib.pa_mainloop_wakeup pa_mainloop_wakeup.restype = None pa_mainloop_wakeup.argtypes = [POINTER(pa_mainloop)] class struct_pollfd(Structure): __slots__ = [ ] struct_pollfd._fields_ = [ ('_opaque_struct', c_int) ] class struct_pollfd(Structure): __slots__ = [ ] struct_pollfd._fields_ = [ ('_opaque_struct', c_int) ] pa_poll_func = CFUNCTYPE(c_int, POINTER(struct_pollfd), c_ulong, c_int, POINTER(None)) # /usr/include/pulse/mainloop.h:123 # /usr/include/pulse/mainloop.h:126 pa_mainloop_set_poll_func = _lib.pa_mainloop_set_poll_func pa_mainloop_set_poll_func.restype = None pa_mainloop_set_poll_func.argtypes = [POINTER(pa_mainloop), pa_poll_func, POINTER(None)] # /usr/include/pulse/mainloop-signal.h:43 pa_signal_init = _lib.pa_signal_init pa_signal_init.restype = c_int pa_signal_init.argtypes = [POINTER(pa_mainloop_api)] # /usr/include/pulse/mainloop-signal.h:46 pa_signal_done = _lib.pa_signal_done pa_signal_done.restype = None pa_signal_done.argtypes = [] class struct_pa_signal_event(Structure): __slots__ = [ ] struct_pa_signal_event._fields_ = [ ('_opaque_struct', c_int) ] class struct_pa_signal_event(Structure): __slots__ = [ ] struct_pa_signal_event._fields_ = [ ('_opaque_struct', c_int) ] pa_signal_event = struct_pa_signal_event # /usr/include/pulse/mainloop-signal.h:49 # /usr/include/pulse/mainloop-signal.h:52 pa_signal_new = _lib.pa_signal_new pa_signal_new.restype = POINTER(pa_signal_event) pa_signal_new.argtypes = [c_int, CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_signal_event), c_int, POINTER(None)), POINTER(None)] # /usr/include/pulse/mainloop-signal.h:55 pa_signal_free = _lib.pa_signal_free pa_signal_free.restype = None pa_signal_free.argtypes = [POINTER(pa_signal_event)] # /usr/include/pulse/mainloop-signal.h:58 pa_signal_set_destroy = _lib.pa_signal_set_destroy pa_signal_set_destroy.restype = None pa_signal_set_destroy.argtypes = [POINTER(pa_signal_event), CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_signal_event), POINTER(None))] # /usr/include/pulse/util.h:38 pa_get_user_name = _lib.pa_get_user_name pa_get_user_name.restype = c_char_p pa_get_user_name.argtypes = [c_char_p, c_size_t] # /usr/include/pulse/util.h:41 pa_get_host_name = _lib.pa_get_host_name pa_get_host_name.restype = c_char_p pa_get_host_name.argtypes = [c_char_p, c_size_t] # /usr/include/pulse/util.h:44 pa_get_fqdn = _lib.pa_get_fqdn pa_get_fqdn.restype = c_char_p pa_get_fqdn.argtypes = [c_char_p, c_size_t] # /usr/include/pulse/util.h:47 pa_get_home_dir = _lib.pa_get_home_dir pa_get_home_dir.restype = c_char_p pa_get_home_dir.argtypes = [c_char_p, c_size_t] # /usr/include/pulse/util.h:51 pa_get_binary_name = _lib.pa_get_binary_name pa_get_binary_name.restype = c_char_p pa_get_binary_name.argtypes = [c_char_p, c_size_t] # /usr/include/pulse/util.h:55 pa_path_get_filename = _lib.pa_path_get_filename pa_path_get_filename.restype = c_char_p pa_path_get_filename.argtypes = [c_char_p] # /usr/include/pulse/util.h:58 pa_msleep = _lib.pa_msleep pa_msleep.restype = c_int pa_msleep.argtypes = [c_ulong] PA_MSEC_PER_SEC = 1000 # /usr/include/pulse/timeval.h:36 PA_USEC_PER_SEC = 1000000 # /usr/include/pulse/timeval.h:37 PA_NSEC_PER_SEC = 1000000000 # /usr/include/pulse/timeval.h:38 PA_USEC_PER_MSEC = 1000 # /usr/include/pulse/timeval.h:39 class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/pulse/timeval.h:44 pa_gettimeofday = _lib.pa_gettimeofday pa_gettimeofday.restype = POINTER(struct_timeval) pa_gettimeofday.argtypes = [POINTER(struct_timeval)] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/pulse/timeval.h:48 pa_timeval_diff = _lib.pa_timeval_diff pa_timeval_diff.restype = pa_usec_t pa_timeval_diff.argtypes = [POINTER(struct_timeval), POINTER(struct_timeval)] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/pulse/timeval.h:51 pa_timeval_cmp = _lib.pa_timeval_cmp pa_timeval_cmp.restype = c_int pa_timeval_cmp.argtypes = [POINTER(struct_timeval), POINTER(struct_timeval)] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/pulse/timeval.h:54 pa_timeval_age = _lib.pa_timeval_age pa_timeval_age.restype = pa_usec_t pa_timeval_age.argtypes = [POINTER(struct_timeval)] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/pulse/timeval.h:57 pa_timeval_add = _lib.pa_timeval_add pa_timeval_add.restype = POINTER(struct_timeval) pa_timeval_add.argtypes = [POINTER(struct_timeval), pa_usec_t] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/pulse/timeval.h:60 pa_timeval_store = _lib.pa_timeval_store pa_timeval_store.restype = POINTER(struct_timeval) pa_timeval_store.argtypes = [POINTER(struct_timeval), pa_usec_t] class struct_timeval(Structure): __slots__ = [ ] struct_timeval._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/pulse/timeval.h:63 pa_timeval_load = _lib.pa_timeval_load pa_timeval_load.restype = pa_usec_t pa_timeval_load.argtypes = [POINTER(struct_timeval)] __all__ = ['pa_mainloop_api', 'pa_io_event_flags_t', 'PA_IO_EVENT_NULL', 'PA_IO_EVENT_INPUT', 'PA_IO_EVENT_OUTPUT', 'PA_IO_EVENT_HANGUP', 'PA_IO_EVENT_ERROR', 'pa_io_event', 'pa_io_event_cb_t', 'pa_io_event_destroy_cb_t', 'pa_time_event', 'pa_time_event_cb_t', 'pa_time_event_destroy_cb_t', 'pa_defer_event', 'pa_defer_event_cb_t', 'pa_defer_event_destroy_cb_t', 'pa_mainloop_api_once', 'PA_CHANNELS_MAX', 'PA_RATE_MAX', 'pa_sample_format_t', 'PA_SAMPLE_U8', 'PA_SAMPLE_ALAW', 'PA_SAMPLE_ULAW', 'PA_SAMPLE_S16LE', 'PA_SAMPLE_S16BE', 'PA_SAMPLE_FLOAT32LE', 'PA_SAMPLE_FLOAT32BE', 'PA_SAMPLE_S32LE', 'PA_SAMPLE_S32BE', 'PA_SAMPLE_MAX', 'PA_SAMPLE_INVALID', 'pa_sample_spec', 'pa_usec_t', 'pa_bytes_per_second', 'pa_frame_size', 'pa_sample_size', 'pa_bytes_to_usec', 'pa_usec_to_bytes', 'pa_sample_spec_valid', 'pa_sample_spec_equal', 'pa_sample_format_to_string', 'pa_parse_sample_format', 'PA_SAMPLE_SPEC_SNPRINT_MAX', 'pa_sample_spec_snprint', 'pa_bytes_snprint', 'pa_context_state_t', 'PA_CONTEXT_UNCONNECTED', 'PA_CONTEXT_CONNECTING', 'PA_CONTEXT_AUTHORIZING', 'PA_CONTEXT_SETTING_NAME', 'PA_CONTEXT_READY', 'PA_CONTEXT_FAILED', 'PA_CONTEXT_TERMINATED', 'pa_stream_state_t', 'PA_STREAM_UNCONNECTED', 'PA_STREAM_CREATING', 'PA_STREAM_READY', 'PA_STREAM_FAILED', 'PA_STREAM_TERMINATED', 'pa_operation_state_t', 'PA_OPERATION_RUNNING', 'PA_OPERATION_DONE', 'PA_OPERATION_CANCELED', 'pa_context_flags_t', 'PA_CONTEXT_NOAUTOSPAWN', 'pa_stream_direction_t', 'PA_STREAM_NODIRECTION', 'PA_STREAM_PLAYBACK', 'PA_STREAM_RECORD', 'PA_STREAM_UPLOAD', 'pa_stream_flags_t', 'PA_STREAM_START_CORKED', 'PA_STREAM_INTERPOLATE_TIMING', 'PA_STREAM_NOT_MONOTONOUS', 'PA_STREAM_AUTO_TIMING_UPDATE', 'PA_STREAM_NO_REMAP_CHANNELS', 'PA_STREAM_NO_REMIX_CHANNELS', 'PA_STREAM_FIX_FORMAT', 'PA_STREAM_FIX_RATE', 'PA_STREAM_FIX_CHANNELS', 'PA_STREAM_DONT_MOVE', 'PA_STREAM_VARIABLE_RATE', 'pa_buffer_attr', 'pa_subscription_mask_t', 'PA_SUBSCRIPTION_MASK_NULL', 'PA_SUBSCRIPTION_MASK_SINK', 'PA_SUBSCRIPTION_MASK_SOURCE', 'PA_SUBSCRIPTION_MASK_SINK_INPUT', 'PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT', 'PA_SUBSCRIPTION_MASK_MODULE', 'PA_SUBSCRIPTION_MASK_CLIENT', 'PA_SUBSCRIPTION_MASK_SAMPLE_CACHE', 'PA_SUBSCRIPTION_MASK_SERVER', 'PA_SUBSCRIPTION_MASK_AUTOLOAD', 'PA_SUBSCRIPTION_MASK_ALL', 'pa_subscription_event_type_t', 'PA_SUBSCRIPTION_EVENT_SINK', 'PA_SUBSCRIPTION_EVENT_SOURCE', 'PA_SUBSCRIPTION_EVENT_SINK_INPUT', 'PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT', 'PA_SUBSCRIPTION_EVENT_MODULE', 'PA_SUBSCRIPTION_EVENT_CLIENT', 'PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE', 'PA_SUBSCRIPTION_EVENT_SERVER', 'PA_SUBSCRIPTION_EVENT_AUTOLOAD', 'PA_SUBSCRIPTION_EVENT_FACILITY_MASK', 'PA_SUBSCRIPTION_EVENT_NEW', 'PA_SUBSCRIPTION_EVENT_CHANGE', 'PA_SUBSCRIPTION_EVENT_REMOVE', 'PA_SUBSCRIPTION_EVENT_TYPE_MASK', 'pa_timing_info', 'pa_spawn_api', 'pa_seek_mode_t', 'PA_SEEK_RELATIVE', 'PA_SEEK_ABSOLUTE', 'PA_SEEK_RELATIVE_ON_READ', 'PA_SEEK_RELATIVE_END', 'pa_sink_flags_t', 'PA_SINK_HW_VOLUME_CTRL', 'PA_SINK_LATENCY', 'PA_SINK_HARDWARE', 'PA_SINK_NETWORK', 'pa_source_flags_t', 'PA_SOURCE_HW_VOLUME_CTRL', 'PA_SOURCE_LATENCY', 'PA_SOURCE_HARDWARE', 'PA_SOURCE_NETWORK', 'pa_free_cb_t', 'pa_operation', 'pa_operation_ref', 'pa_operation_unref', 'pa_operation_cancel', 'pa_operation_get_state', 'pa_context', 'pa_context_notify_cb_t', 'pa_context_success_cb_t', 'pa_context_new', 'pa_context_unref', 'pa_context_ref', 'pa_context_set_state_callback', 'pa_context_errno', 'pa_context_is_pending', 'pa_context_get_state', 'pa_context_connect', 'pa_context_disconnect', 'pa_context_drain', 'pa_context_exit_daemon', 'pa_context_set_default_sink', 'pa_context_set_default_source', 'pa_context_is_local', 'pa_context_set_name', 'pa_context_get_server', 'pa_context_get_protocol_version', 'pa_context_get_server_protocol_version', 'pa_channel_position_t', 'PA_CHANNEL_POSITION_INVALID', 'PA_CHANNEL_POSITION_MONO', 'PA_CHANNEL_POSITION_LEFT', 'PA_CHANNEL_POSITION_RIGHT', 'PA_CHANNEL_POSITION_CENTER', 'PA_CHANNEL_POSITION_FRONT_LEFT', 'PA_CHANNEL_POSITION_FRONT_RIGHT', 'PA_CHANNEL_POSITION_FRONT_CENTER', 'PA_CHANNEL_POSITION_REAR_CENTER', 'PA_CHANNEL_POSITION_REAR_LEFT', 'PA_CHANNEL_POSITION_REAR_RIGHT', 'PA_CHANNEL_POSITION_LFE', 'PA_CHANNEL_POSITION_SUBWOOFER', 'PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER', 'PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER', 'PA_CHANNEL_POSITION_SIDE_LEFT', 'PA_CHANNEL_POSITION_SIDE_RIGHT', 'PA_CHANNEL_POSITION_AUX0', 'PA_CHANNEL_POSITION_AUX1', 'PA_CHANNEL_POSITION_AUX2', 'PA_CHANNEL_POSITION_AUX3', 'PA_CHANNEL_POSITION_AUX4', 'PA_CHANNEL_POSITION_AUX5', 'PA_CHANNEL_POSITION_AUX6', 'PA_CHANNEL_POSITION_AUX7', 'PA_CHANNEL_POSITION_AUX8', 'PA_CHANNEL_POSITION_AUX9', 'PA_CHANNEL_POSITION_AUX10', 'PA_CHANNEL_POSITION_AUX11', 'PA_CHANNEL_POSITION_AUX12', 'PA_CHANNEL_POSITION_AUX13', 'PA_CHANNEL_POSITION_AUX14', 'PA_CHANNEL_POSITION_AUX15', 'PA_CHANNEL_POSITION_AUX16', 'PA_CHANNEL_POSITION_AUX17', 'PA_CHANNEL_POSITION_AUX18', 'PA_CHANNEL_POSITION_AUX19', 'PA_CHANNEL_POSITION_AUX20', 'PA_CHANNEL_POSITION_AUX21', 'PA_CHANNEL_POSITION_AUX22', 'PA_CHANNEL_POSITION_AUX23', 'PA_CHANNEL_POSITION_AUX24', 'PA_CHANNEL_POSITION_AUX25', 'PA_CHANNEL_POSITION_AUX26', 'PA_CHANNEL_POSITION_AUX27', 'PA_CHANNEL_POSITION_AUX28', 'PA_CHANNEL_POSITION_AUX29', 'PA_CHANNEL_POSITION_AUX30', 'PA_CHANNEL_POSITION_AUX31', 'PA_CHANNEL_POSITION_TOP_CENTER', 'PA_CHANNEL_POSITION_TOP_FRONT_LEFT', 'PA_CHANNEL_POSITION_TOP_FRONT_RIGHT', 'PA_CHANNEL_POSITION_TOP_FRONT_CENTER', 'PA_CHANNEL_POSITION_TOP_REAR_LEFT', 'PA_CHANNEL_POSITION_TOP_REAR_RIGHT', 'PA_CHANNEL_POSITION_TOP_REAR_CENTER', 'PA_CHANNEL_POSITION_MAX', 'pa_channel_map_def_t', 'PA_CHANNEL_MAP_AIFF', 'PA_CHANNEL_MAP_ALSA', 'PA_CHANNEL_MAP_AUX', 'PA_CHANNEL_MAP_WAVEEX', 'PA_CHANNEL_MAP_OSS', 'PA_CHANNEL_MAP_DEFAULT', 'pa_channel_map', 'pa_channel_map_init', 'pa_channel_map_init_mono', 'pa_channel_map_init_stereo', 'pa_channel_map_init_auto', 'pa_channel_position_to_string', 'pa_channel_position_to_pretty_string', 'PA_CHANNEL_MAP_SNPRINT_MAX', 'pa_channel_map_snprint', 'pa_channel_map_parse', 'pa_channel_map_equal', 'pa_channel_map_valid', 'pa_volume_t', 'PA_VOLUME_NORM', 'PA_VOLUME_MUTED', 'pa_cvolume', 'pa_cvolume_equal', 'pa_cvolume_set', 'PA_CVOLUME_SNPRINT_MAX', 'pa_cvolume_snprint', 'pa_cvolume_avg', 'pa_cvolume_valid', 'pa_cvolume_channels_equal_to', 'pa_sw_volume_multiply', 'pa_sw_cvolume_multiply', 'pa_sw_volume_from_dB', 'pa_sw_volume_to_dB', 'pa_sw_volume_from_linear', 'pa_sw_volume_to_linear', 'PA_DECIBEL_MININFTY', 'pa_stream', 'pa_stream_success_cb_t', 'pa_stream_request_cb_t', 'pa_stream_notify_cb_t', 'pa_stream_new', 'pa_stream_unref', 'pa_stream_ref', 'pa_stream_get_state', 'pa_stream_get_context', 'pa_stream_get_index', 'pa_stream_get_device_index', 'pa_stream_get_device_name', 'pa_stream_is_suspended', 'pa_stream_connect_playback', 'pa_stream_connect_record', 'pa_stream_disconnect', 'pa_stream_write', 'pa_stream_peek', 'pa_stream_drop', 'pa_stream_writable_size', 'pa_stream_readable_size', 'pa_stream_drain', 'pa_stream_update_timing_info', 'pa_stream_set_state_callback', 'pa_stream_set_write_callback', 'pa_stream_set_read_callback', 'pa_stream_set_overflow_callback', 'pa_stream_set_underflow_callback', 'pa_stream_set_latency_update_callback', 'pa_stream_set_moved_callback', 'pa_stream_set_suspended_callback', 'pa_stream_cork', 'pa_stream_flush', 'pa_stream_prebuf', 'pa_stream_trigger', 'pa_stream_set_name', 'pa_stream_get_time', 'pa_stream_get_latency', 'pa_stream_get_timing_info', 'pa_stream_get_sample_spec', 'pa_stream_get_channel_map', 'pa_stream_get_buffer_attr', 'pa_stream_set_buffer_attr', 'pa_stream_update_sample_rate', 'pa_sink_info', 'pa_sink_info_cb_t', 'pa_context_get_sink_info_by_name', 'pa_context_get_sink_info_by_index', 'pa_context_get_sink_info_list', 'pa_source_info', 'pa_source_info_cb_t', 'pa_context_get_source_info_by_name', 'pa_context_get_source_info_by_index', 'pa_context_get_source_info_list', 'pa_server_info', 'pa_server_info_cb_t', 'pa_context_get_server_info', 'pa_module_info', 'pa_module_info_cb_t', 'pa_context_get_module_info', 'pa_context_get_module_info_list', 'pa_client_info', 'pa_client_info_cb_t', 'pa_context_get_client_info', 'pa_context_get_client_info_list', 'pa_sink_input_info', 'pa_sink_input_info_cb_t', 'pa_context_get_sink_input_info', 'pa_context_get_sink_input_info_list', 'pa_source_output_info', 'pa_source_output_info_cb_t', 'pa_context_get_source_output_info', 'pa_context_get_source_output_info_list', 'pa_context_set_sink_volume_by_index', 'pa_context_set_sink_volume_by_name', 'pa_context_set_sink_mute_by_index', 'pa_context_set_sink_mute_by_name', 'pa_context_set_sink_input_volume', 'pa_context_set_sink_input_mute', 'pa_context_set_source_volume_by_index', 'pa_context_set_source_volume_by_name', 'pa_context_set_source_mute_by_index', 'pa_context_set_source_mute_by_name', 'pa_stat_info', 'pa_stat_info_cb_t', 'pa_context_stat', 'pa_sample_info', 'pa_sample_info_cb_t', 'pa_context_get_sample_info_by_name', 'pa_context_get_sample_info_by_index', 'pa_context_get_sample_info_list', 'pa_context_kill_client', 'pa_context_kill_sink_input', 'pa_context_kill_source_output', 'pa_context_index_cb_t', 'pa_context_load_module', 'pa_context_unload_module', 'pa_autoload_type_t', 'PA_AUTOLOAD_SINK', 'PA_AUTOLOAD_SOURCE', 'pa_autoload_info', 'pa_autoload_info_cb_t', 'pa_context_get_autoload_info_by_name', 'pa_context_get_autoload_info_by_index', 'pa_context_get_autoload_info_list', 'pa_context_add_autoload', 'pa_context_remove_autoload_by_name', 'pa_context_remove_autoload_by_index', 'pa_context_move_sink_input_by_name', 'pa_context_move_sink_input_by_index', 'pa_context_move_source_output_by_name', 'pa_context_move_source_output_by_index', 'pa_context_suspend_sink_by_name', 'pa_context_suspend_sink_by_index', 'pa_context_suspend_source_by_name', 'pa_context_suspend_source_by_index', 'pa_context_subscribe_cb_t', 'pa_context_subscribe', 'pa_context_set_subscribe_callback', 'pa_stream_connect_upload', 'pa_stream_finish_upload', 'pa_context_play_sample', 'pa_context_remove_sample', 'pa_get_library_version', 'PA_API_VERSION', 'PA_PROTOCOL_VERSION', 'pa_strerror', 'pa_xmalloc', 'pa_xmalloc0', 'pa_xrealloc', 'pa_xfree', 'pa_xstrdup', 'pa_xstrndup', 'pa_xmemdup', 'pa_utf8_valid', 'pa_utf8_filter', 'pa_utf8_to_locale', 'pa_locale_to_utf8', 'pa_threaded_mainloop', 'pa_threaded_mainloop_new', 'pa_threaded_mainloop_free', 'pa_threaded_mainloop_start', 'pa_threaded_mainloop_stop', 'pa_threaded_mainloop_lock', 'pa_threaded_mainloop_unlock', 'pa_threaded_mainloop_wait', 'pa_threaded_mainloop_signal', 'pa_threaded_mainloop_accept', 'pa_threaded_mainloop_get_retval', 'pa_threaded_mainloop_get_api', 'pa_threaded_mainloop_in_thread', 'pa_mainloop', 'pa_mainloop_new', 'pa_mainloop_free', 'pa_mainloop_prepare', 'pa_mainloop_poll', 'pa_mainloop_dispatch', 'pa_mainloop_get_retval', 'pa_mainloop_iterate', 'pa_mainloop_run', 'pa_mainloop_get_api', 'pa_mainloop_quit', 'pa_mainloop_wakeup', 'pa_poll_func', 'pa_mainloop_set_poll_func', 'pa_signal_init', 'pa_signal_done', 'pa_signal_event', 'pa_signal_new', 'pa_signal_free', 'pa_signal_set_destroy', 'pa_get_user_name', 'pa_get_host_name', 'pa_get_fqdn', 'pa_get_home_dir', 'pa_get_binary_name', 'pa_path_get_filename', 'pa_msleep', 'PA_MSEC_PER_SEC', 'PA_USEC_PER_SEC', 'PA_NSEC_PER_SEC', 'PA_USEC_PER_MSEC', 'pa_gettimeofday', 'pa_timeval_diff', 'pa_timeval_cmp', 'pa_timeval_age', 'pa_timeval_add', 'pa_timeval_store', 'pa_timeval_load']
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id:$ import ctypes from pyglet import com lib = ctypes.oledll.dsound DWORD = ctypes.c_uint32 LPDWORD = ctypes.POINTER(DWORD) LONG = ctypes.c_long LPLONG = ctypes.POINTER(LONG) WORD = ctypes.c_uint16 HWND = DWORD LPUNKNOWN = ctypes.c_void_p D3DVALUE = ctypes.c_float PD3DVALUE = ctypes.POINTER(D3DVALUE) class D3DVECTOR(ctypes.Structure): _fields_ = [ ('x', ctypes.c_float), ('y', ctypes.c_float), ('z', ctypes.c_float), ] PD3DVECTOR = ctypes.POINTER(D3DVECTOR) class WAVEFORMATEX(ctypes.Structure): _fields_ = [ ('wFormatTag', WORD), ('nChannels', WORD), ('nSamplesPerSec', DWORD), ('nAvgBytesPerSec', DWORD), ('nBlockAlign', WORD), ('wBitsPerSample', WORD), ('cbSize', WORD), ] LPWAVEFORMATEX = ctypes.POINTER(WAVEFORMATEX) WAVE_FORMAT_PCM = 1 class DSCAPS(ctypes.Structure): _fields_ = [ ('dwSize', DWORD), ('dwFlags', DWORD), ('dwMinSecondarySampleRate', DWORD), ('dwMaxSecondarySampleRate', DWORD), ('dwPrimaryBuffers', DWORD), ('dwMaxHwMixingAllBuffers', DWORD), ('dwMaxHwMixingStaticBuffers', DWORD), ('dwMaxHwMixingStreamingBuffers', DWORD), ('dwFreeHwMixingAllBuffers', DWORD), ('dwFreeHwMixingStaticBuffers', DWORD), ('dwFreeHwMixingStreamingBuffers', DWORD), ('dwMaxHw3DAllBuffers', DWORD), ('dwMaxHw3DStaticBuffers', DWORD), ('dwMaxHw3DStreamingBuffers', DWORD), ('dwFreeHw3DAllBuffers', DWORD), ('dwFreeHw3DStaticBuffers', DWORD), ('dwFreeHw3DStreamingBuffers', DWORD), ('dwTotalHwMemBytes', DWORD), ('dwFreeHwMemBytes', DWORD), ('dwMaxContigFreeHwMemBytes', DWORD), ('dwUnlockTransferRateHwBuffers', DWORD), ('dwPlayCpuOverheadSwBuffers', DWORD), ('dwReserved1', DWORD), ('dwReserved2', DWORD) ] LPDSCAPS = ctypes.POINTER(DSCAPS) class DSBCAPS(ctypes.Structure): _fields_ = [ ('dwSize', DWORD), ('dwFlags', DWORD), ('dwBufferBytes', DWORD), ('dwUnlockTransferRate', DWORD), ('dwPlayCpuOverhead', DWORD), ] LPDSBCAPS = ctypes.POINTER(DSBCAPS) class DSBUFFERDESC(ctypes.Structure): _fields_ = [ ('dwSize', DWORD), ('dwFlags', DWORD), ('dwBufferBytes', DWORD), ('dwReserved', DWORD), ('lpwfxFormat', LPWAVEFORMATEX), ] LPDSBUFFERDESC = ctypes.POINTER(DSBUFFERDESC) class DS3DBUFFER(ctypes.Structure): _fields_ = [ ('dwSize', DWORD), ('vPosition', D3DVECTOR), ('vVelocity', D3DVECTOR), ('dwInsideConeAngle', DWORD), ('dwOutsideConeAngle', DWORD), ('vConeOrientation', D3DVECTOR), ('lConeOutsideVolume', LONG), ('flMinDistance', D3DVALUE), ('flMaxDistance', D3DVALUE), ('dwMode', DWORD), ] LPDS3DBUFFER = ctypes.POINTER(DS3DBUFFER) class DS3DLISTENER(ctypes.Structure): _fields_ = [ ('dwSize', DWORD), ('vPosition', D3DVECTOR), ('vVelocity', D3DVECTOR), ('vOrientFront', D3DVECTOR), ('vOrientTop', D3DVECTOR), ('flDistanceFactor', D3DVALUE), ('flRolloffFactor', D3DVALUE), ('flDopplerFactor', D3DVALUE), ] LPDS3DLISTENER = ctypes.POINTER(DS3DLISTENER) class IDirectSoundBuffer(com.IUnknown): _methods_ = [ ('GetCaps', com.STDMETHOD(LPDSBCAPS)), ('GetCurrentPosition', com.STDMETHOD(LPDWORD, LPDWORD)), ('GetFormat', com.STDMETHOD(LPWAVEFORMATEX, DWORD, LPDWORD)), ('GetVolume', com.STDMETHOD(LPLONG)), ('GetPan', com.STDMETHOD(LPLONG)), ('GetFrequency', com.STDMETHOD(LPDWORD)), ('GetStatus', com.STDMETHOD(LPDWORD)), ('Initialize', com.STDMETHOD(ctypes.c_void_p, LPDSBUFFERDESC)), ('Lock', com.STDMETHOD(DWORD, DWORD, ctypes.POINTER(ctypes.c_void_p), LPDWORD, ctypes.POINTER(ctypes.c_void_p), LPDWORD, DWORD)), ('Play', com.STDMETHOD(DWORD, DWORD, DWORD)), ('SetCurrentPosition', com.STDMETHOD(DWORD)), ('SetFormat', com.STDMETHOD(LPWAVEFORMATEX)), ('SetVolume', com.STDMETHOD(LONG)), ('SetPan', com.STDMETHOD(LONG)), ('SetFrequency', com.STDMETHOD(DWORD)), ('Stop', com.STDMETHOD()), ('Unlock', com.STDMETHOD(ctypes.c_void_p, DWORD, ctypes.c_void_p, DWORD)), ('Restore', com.STDMETHOD()), ] IID_IDirectSound3DListener = com.GUID( 0x279AFA84, 0x4981, 0x11CE, 0xA5, 0x21, 0x00, 0x20, 0xAF, 0x0B, 0xE5, 0x60) class IDirectSound3DListener(com.IUnknown): _methods_ = [ ('GetAllParameters', com.STDMETHOD(LPDS3DLISTENER)), ('GetDistanceFactor', com.STDMETHOD(PD3DVALUE)), ('GetDopplerFactor', com.STDMETHOD(PD3DVALUE)), ('GetOrientation', com.STDMETHOD(PD3DVECTOR)), ('GetPosition', com.STDMETHOD(PD3DVECTOR)), ('GetRolloffFactor', com.STDMETHOD(PD3DVALUE)), ('GetVelocity', com.STDMETHOD(PD3DVECTOR)), ('SetAllParameters', com.STDMETHOD(LPDS3DLISTENER)), ('SetDistanceFactor', com.STDMETHOD(D3DVALUE, DWORD)), ('SetDopplerFactor', com.STDMETHOD(D3DVALUE, DWORD)), ('SetOrientation', com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE, D3DVALUE, D3DVALUE, D3DVALUE, DWORD)), ('SetPosition', com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE, DWORD)), ('SetRolloffFactor', com.STDMETHOD(D3DVALUE, DWORD)), ('SetVelocity', com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE, DWORD)), ('CommitDeferredSettings', com.STDMETHOD()), ] IID_IDirectSound3DBuffer = com.GUID( 0x279AFA86, 0x4981, 0x11CE, 0xA5, 0x21, 0x00, 0x20, 0xAF, 0x0B, 0xE5, 0x60) class IDirectSound3DBuffer(com.IUnknown): _methods_ = [ ('GetAllParameters', com.STDMETHOD(LPDS3DBUFFER)), ('GetConeAngles', com.STDMETHOD(LPDWORD, LPDWORD)), ('GetConeOrientation', com.STDMETHOD(PD3DVECTOR)), ('GetConeOutsideVolume', com.STDMETHOD(LPLONG)), ('GetMaxDistance', com.STDMETHOD(PD3DVALUE)), ('GetMinDistance', com.STDMETHOD(PD3DVALUE)), ('GetMode', com.STDMETHOD(LPDWORD)), ('GetPosition', com.STDMETHOD(PD3DVECTOR)), ('GetVelocity', com.STDMETHOD(PD3DVECTOR)), ('SetAllParameters', com.STDMETHOD(LPDS3DBUFFER, DWORD)), ('SetConeAngles', com.STDMETHOD(DWORD, DWORD, DWORD)), ('SetConeOrientation', com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE, DWORD)), ('SetConeOutsideVolume', com.STDMETHOD(LONG, DWORD)), ('SetMaxDistance', com.STDMETHOD(D3DVALUE, DWORD)), ('SetMinDistance', com.STDMETHOD(D3DVALUE, DWORD)), ('SetMode', com.STDMETHOD(DWORD, DWORD)), ('SetPosition', com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE, DWORD)), ('SetVelocity', com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE, DWORD)), ] class IDirectSound(com.IUnknown): _methods_ = [ ('CreateSoundBuffer', com.STDMETHOD(LPDSBUFFERDESC, ctypes.POINTER(IDirectSoundBuffer), LPUNKNOWN)), ('GetCaps', com.STDMETHOD(LPDSCAPS)), ('DuplicateSoundBuffer', com.STDMETHOD(IDirectSoundBuffer, ctypes.POINTER(IDirectSoundBuffer))), ('SetCooperativeLevel', com.STDMETHOD(HWND, DWORD)), ('Compact', com.STDMETHOD()), ('GetSpeakerConfig', com.STDMETHOD(LPDWORD)), ('SetSpeakerConfig', com.STDMETHOD(DWORD)), ('Initialize', com.STDMETHOD(com.LPGUID)), ] _type_ = com.COMInterface DirectSoundCreate = lib.DirectSoundCreate DirectSoundCreate.argtypes = \ [com.LPGUID, ctypes.POINTER(IDirectSound), ctypes.c_void_p] DSCAPS_PRIMARYMONO = 0x00000001 DSCAPS_PRIMARYSTEREO = 0x00000002 DSCAPS_PRIMARY8BIT = 0x00000004 DSCAPS_PRIMARY16BIT = 0x00000008 DSCAPS_CONTINUOUSRATE = 0x00000010 DSCAPS_EMULDRIVER = 0x00000020 DSCAPS_CERTIFIED = 0x00000040 DSCAPS_SECONDARYMONO = 0x00000100 DSCAPS_SECONDARYSTEREO = 0x00000200 DSCAPS_SECONDARY8BIT = 0x00000400 DSCAPS_SECONDARY16BIT = 0x00000800 DSSCL_NORMAL = 0x00000001 DSSCL_PRIORITY = 0x00000002 DSSCL_EXCLUSIVE = 0x00000003 DSSCL_WRITEPRIMARY = 0x00000004 DSSPEAKER_DIRECTOUT = 0x00000000 DSSPEAKER_HEADPHONE = 0x00000001 DSSPEAKER_MONO = 0x00000002 DSSPEAKER_QUAD = 0x00000003 DSSPEAKER_STEREO = 0x00000004 DSSPEAKER_SURROUND = 0x00000005 DSSPEAKER_5POINT1 = 0x00000006 DSSPEAKER_7POINT1 = 0x00000007 DSSPEAKER_GEOMETRY_MIN = 0x00000005 # 5 degrees DSSPEAKER_GEOMETRY_NARROW = 0x0000000A # 10 degrees DSSPEAKER_GEOMETRY_WIDE = 0x00000014 # 20 degrees DSSPEAKER_GEOMETRY_MAX = 0x000000B4 # 180 degrees DSBCAPS_PRIMARYBUFFER = 0x00000001 DSBCAPS_STATIC = 0x00000002 DSBCAPS_LOCHARDWARE = 0x00000004 DSBCAPS_LOCSOFTWARE = 0x00000008 DSBCAPS_CTRL3D = 0x00000010 DSBCAPS_CTRLFREQUENCY = 0x00000020 DSBCAPS_CTRLPAN = 0x00000040 DSBCAPS_CTRLVOLUME = 0x00000080 DSBCAPS_CTRLPOSITIONNOTIFY = 0x00000100 DSBCAPS_CTRLFX = 0x00000200 DSBCAPS_STICKYFOCUS = 0x00004000 DSBCAPS_GLOBALFOCUS = 0x00008000 DSBCAPS_GETCURRENTPOSITION2 = 0x00010000 DSBCAPS_MUTE3DATMAXDISTANCE = 0x00020000 DSBCAPS_LOCDEFER = 0x00040000 DSBPLAY_LOOPING = 0x00000001 DSBPLAY_LOCHARDWARE = 0x00000002 DSBPLAY_LOCSOFTWARE = 0x00000004 DSBPLAY_TERMINATEBY_TIME = 0x00000008 DSBPLAY_TERMINATEBY_DISTANCE = 0x000000010 DSBPLAY_TERMINATEBY_PRIORITY = 0x000000020 DSBSTATUS_PLAYING = 0x00000001 DSBSTATUS_BUFFERLOST = 0x00000002 DSBSTATUS_LOOPING = 0x00000004 DSBSTATUS_LOCHARDWARE = 0x00000008 DSBSTATUS_LOCSOFTWARE = 0x00000010 DSBSTATUS_TERMINATED = 0x00000020 DSBLOCK_FROMWRITECURSOR = 0x00000001 DSBLOCK_ENTIREBUFFER = 0x00000002 DSBFREQUENCY_MIN = 100 DSBFREQUENCY_MAX = 100000 DSBFREQUENCY_ORIGINAL = 0 DSBPAN_LEFT = -10000 DSBPAN_CENTER = 0 DSBPAN_RIGHT = 10000 DSBVOLUME_MIN = -10000 DSBVOLUME_MAX = 0 DSBSIZE_MIN = 4 DSBSIZE_MAX = 0x0FFFFFFF DSBSIZE_FX_MIN = 150 # NOTE: Milliseconds, not bytes DS3DMODE_NORMAL = 0x00000000 DS3DMODE_HEADRELATIVE = 0x00000001 DS3DMODE_DISABLE = 0x00000002 DS3D_IMMEDIATE = 0x00000000 DS3D_DEFERRED = 0x00000001 DS3D_MINDISTANCEFACTOR = -1000000.0 # XXX FLT_MIN DS3D_MAXDISTANCEFACTOR = 1000000.0 # XXX FLT_MAX DS3D_DEFAULTDISTANCEFACTOR = 1.0 DS3D_MINROLLOFFFACTOR = 0.0 DS3D_MAXROLLOFFFACTOR = 10.0 DS3D_DEFAULTROLLOFFFACTOR = 1.0 DS3D_MINDOPPLERFACTOR = 0.0 DS3D_MAXDOPPLERFACTOR = 10.0 DS3D_DEFAULTDOPPLERFACTOR = 1.0 DS3D_DEFAULTMINDISTANCE = 1.0 DS3D_DEFAULTMAXDISTANCE = 1000000000.0 DS3D_MINCONEANGLE = 0 DS3D_MAXCONEANGLE = 360 DS3D_DEFAULTCONEANGLE = 360 DS3D_DEFAULTCONEOUTSIDEVOLUME = DSBVOLUME_MAX
Python
#!/usr/bin/python # $Id:$ import ctypes import math import sys import threading import time import lib_dsound as lib from pyglet.media import MediaException, MediaThread, AbstractAudioDriver, \ AbstractAudioPlayer, MediaEvent from pyglet.window.win32 import _user32, _kernel32 import pyglet _debug = pyglet.options['debug_media'] class DirectSoundException(MediaException): pass def _db(gain): '''Convert linear gain in range [0.0, 1.0] to 100ths of dB.''' if gain <= 0: return -10000 return max(-10000, min(int(1000 * math.log(min(gain, 1))), 0)) class DirectSoundWorker(MediaThread): _min_write_size = 9600 # Time to wait if there are players, but they're all full. _nap_time = 0.05 # Time to wait if there are no players. _sleep_time = None def __init__(self): super(DirectSoundWorker, self).__init__() self.players = set() def run(self): while True: # This is a big lock, but ensures a player is not deleted while # we're processing it -- this saves on extra checks in the # player's methods that would otherwise have to check that it's # still alive. if _debug: print 'DirectSoundWorker run attempt acquire' self.condition.acquire() if _debug: print 'DirectSoundWorker run acquire' if self.stopped: self.condition.release() break sleep_time = -1 if self.players: player = None write_size = 0 for p in self.players: s = p.get_write_size() if s > write_size: player = p write_size = s if write_size > self._min_write_size: player.refill(write_size) else: sleep_time = self._nap_time else: sleep_time = self._sleep_time self.condition.release() if _debug: print 'DirectSoundWorker run release' if sleep_time != -1: self.sleep(sleep_time) if _debug: print 'DirectSoundWorker exiting' def add(self, player): if _debug: print 'DirectSoundWorker add', player self.condition.acquire() self.players.add(player) self.condition.notify() self.condition.release() if _debug: print 'return DirectSoundWorker add', player def remove(self, player): if _debug: print 'DirectSoundWorker remove', player self.condition.acquire() try: self.players.remove(player) except KeyError: pass self.condition.notify() self.condition.release() if _debug: print 'return DirectSoundWorker remove', player class DirectSoundAudioPlayer(AbstractAudioPlayer): # How many bytes the ring buffer should be _buffer_size = 44800 * 1 # Need to cache these because pyglet API allows update separately, but # DSound requires both to be set at once. _cone_inner_angle = 360 _cone_outer_angle = 360 def __init__(self, source_group, player): super(DirectSoundAudioPlayer, self).__init__(source_group, player) # Locking strategy: # All DirectSound calls should be locked. All instance vars relating # to buffering/filling/time/events should be locked (used by both # application and worker thread). Other instance vars (consts and # 3d vars) do not need to be locked. self._lock = threading.RLock() # Desired play state (may be actually paused due to underrun -- not # implemented yet). self._playing = False # Up to one audio data may be buffered if too much data was received # from the source that could not be written immediately into the # buffer. See refill(). self._next_audio_data = None # Theoretical write and play cursors for an infinite buffer. play # cursor is always <= write cursor (when equal, underrun is # happening). self._write_cursor = 0 self._play_cursor = 0 # Cursor position of end of data. Silence is written after # eos for one buffer size. self._eos_cursor = None # Indexes into DSound circular buffer. Complications ensue wrt each # other to avoid writing over the play cursor. See get_write_size and # write(). self._play_cursor_ring = 0 self._write_cursor_ring = 0 # List of (play_cursor, MediaEvent), in sort order self._events = [] # List of (cursor, timestamp), in sort order (cursor gives expiry # place of the timestamp) self._timestamps = [] audio_format = source_group.audio_format wfx = lib.WAVEFORMATEX() wfx.wFormatTag = lib.WAVE_FORMAT_PCM wfx.nChannels = audio_format.channels wfx.nSamplesPerSec = audio_format.sample_rate wfx.wBitsPerSample = audio_format.sample_size wfx.nBlockAlign = wfx.wBitsPerSample * wfx.nChannels // 8 wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign dsbdesc = lib.DSBUFFERDESC() dsbdesc.dwSize = ctypes.sizeof(dsbdesc) dsbdesc.dwFlags = (lib.DSBCAPS_GLOBALFOCUS | lib.DSBCAPS_GETCURRENTPOSITION2 | lib.DSBCAPS_CTRLFREQUENCY | lib.DSBCAPS_CTRLVOLUME) if audio_format.channels == 1: dsbdesc.dwFlags |= lib.DSBCAPS_CTRL3D dsbdesc.dwBufferBytes = self._buffer_size dsbdesc.lpwfxFormat = ctypes.pointer(wfx) # DSound buffer self._buffer = lib.IDirectSoundBuffer() driver._dsound.CreateSoundBuffer(dsbdesc, ctypes.byref(self._buffer), None) if audio_format.channels == 1: self._buffer3d = lib.IDirectSound3DBuffer() self._buffer.QueryInterface(lib.IID_IDirectSound3DBuffer, ctypes.byref(self._buffer3d)) else: self._buffer3d = None self._buffer.SetCurrentPosition(0) self.refill(self._buffer_size) def __del__(self): try: self.delete() except: pass def delete(self): if driver and driver.worker: driver.worker.remove(self) self.lock() self._buffer.Stop() self._buffer.Release() self._buffer = None if self._buffer3d: self._buffer3d.Release() self._buffer3d = None self.unlock() def lock(self): self._lock.acquire() def unlock(self): self._lock.release() def play(self): if _debug: print 'DirectSound play' driver.worker.add(self) self.lock() if not self._playing: self._playing = True self._buffer.Play(0, 0, lib.DSBPLAY_LOOPING) self.unlock() if _debug: print 'return DirectSound play' def stop(self): if _debug: print 'DirectSound stop' driver.worker.remove(self) self.lock() if self._playing: self._playing = False self._buffer.Stop() self.unlock() if _debug: print 'return DirectSound stop' def clear(self): if _debug: print 'DirectSound clear' self.lock() self._buffer.SetCurrentPosition(0) self._play_cursor_ring = self._write_cursor_ring = 0 self._play_cursor = self._write_cursor self._eos_cursor = None self._next_audio_data = None del self._events[:] del self._timestamps[:] self.unlock() def refill(self, write_size): self.lock() while write_size > 0: if _debug: print 'refill, write_size =', write_size # Get next audio packet (or remains of last one) if self._next_audio_data: audio_data = self._next_audio_data self._next_audio_data = None else: audio_data = self.source_group.get_audio_data(write_size) # Write it, or silence if there are no more packets if audio_data: # Add events for event in audio_data.events: event_cursor = self._write_cursor + event.timestamp * \ self.source_group.audio_format.bytes_per_second self._events.append((event_cursor, event)) # Add timestamp (at end of this data packet) ts_cursor = self._write_cursor + audio_data.length self._timestamps.append( (ts_cursor, audio_data.timestamp + audio_data.duration)) # Write data if _debug: print 'write', audio_data.length length = min(write_size, audio_data.length) self.write(audio_data, length) if audio_data.length: self._next_audio_data = audio_data write_size -= length else: # Write silence if self._eos_cursor is None: self._eos_cursor = self._write_cursor self._events.append( (self._eos_cursor, MediaEvent(0, 'on_eos'))) self._events.append( (self._eos_cursor, MediaEvent(0, 'on_source_group_eos'))) self._events.sort() if self._write_cursor > self._eos_cursor + self._buffer_size: self.stop() else: self.write(None, write_size) write_size = 0 self.unlock() def update_play_cursor(self): self.lock() play_cursor_ring = lib.DWORD() self._buffer.GetCurrentPosition(play_cursor_ring, None) if play_cursor_ring.value < self._play_cursor_ring: # Wrapped around self._play_cursor += self._buffer_size - self._play_cursor_ring self._play_cursor_ring = 0 self._play_cursor += play_cursor_ring.value - self._play_cursor_ring self._play_cursor_ring = play_cursor_ring.value # Dispatch pending events pending_events = [] while self._events and self._events[0][0] <= self._play_cursor: _, event = self._events.pop(0) pending_events.append(event) if _debug: print 'Dispatching pending events:', pending_events print 'Remaining events:', self._events # Remove expired timestamps while self._timestamps and self._timestamps[0][0] < self._play_cursor: del self._timestamps[0] self.unlock() for event in pending_events: event._sync_dispatch_to_player(self.player) def get_write_size(self): self.update_play_cursor() self.lock() play_cursor = self._play_cursor write_cursor = self._write_cursor self.unlock() return self._buffer_size - max(write_cursor - play_cursor, 0) def write(self, audio_data, length): # Pass audio_data=None to write silence if length == 0: return 0 self.lock() p1 = ctypes.c_void_p() l1 = lib.DWORD() p2 = ctypes.c_void_p() l2 = lib.DWORD() assert 0 < length <= self._buffer_size self._buffer.Lock(self._write_cursor_ring, length, ctypes.byref(p1), l1, ctypes.byref(p2), l2, 0) assert length == l1.value + l2.value if audio_data: ctypes.memmove(p1, audio_data.data, l1.value) audio_data.consume(l1.value, self.source_group.audio_format) if l2.value: ctypes.memmove(p2, audio_data.data, l2.value) audio_data.consume(l2.value, self.source_group.audio_format) else: ctypes.memset(p1, 0, l1.value) if l2.value: ctypes.memset(p2, 0, l2.value) self._buffer.Unlock(p1, l1, p2, l2) self._write_cursor += length self._write_cursor_ring += length self._write_cursor_ring %= self._buffer_size self.unlock() def get_time(self): self.lock() if self._timestamps: cursor, ts = self._timestamps[0] result = ts + (self._play_cursor - cursor) / \ float(self.source_group.audio_format.bytes_per_second) else: result = None self.unlock() return result def set_volume(self, volume): volume = _db(volume) self.lock() self._buffer.SetVolume(volume) self.unlock() def set_position(self, position): if self._buffer3d: x, y, z = position self.lock() self._buffer3d.SetPosition(x, y, -z, lib.DS3D_IMMEDIATE) self.unlock() def set_min_distance(self, min_distance): if self._buffer3d: self.lock() self._buffer3d.SetMinDistance(min_distance, lib.DS3D_IMMEDIATE) self.unlock() def set_max_distance(self, max_distance): if self._buffer3d: self.lock() self._buffer3d.SetMaxDistance(max_distance, lib.DS3D_IMMEDIATE) self.unlock() def set_pitch(self, pitch): frequency = int(pitch * self.source_group.audio_format.sample_rate) self.lock() self._buffer.SetFrequency(frequency) self.unlock() def set_cone_orientation(self, cone_orientation): if self._buffer3d: x, y, z = cone_orientation self.lock() self._buffer3d.SetConeOrientation(x, y, -z, lib.DS3D_IMMEDIATE) self.unlock() def set_cone_inner_angle(self, cone_inner_angle): if self._buffer3d: self._cone_inner_angle = int(cone_inner_angle) self._set_cone_angles() def set_cone_outer_angle(self, cone_outer_angle): if self._buffer3d: self._cone_outer_angle = int(cone_outer_angle) self._set_cone_angles() def _set_cone_angles(self): inner = min(self._cone_inner_angle, self._cone_outer_angle) outer = max(self._cone_inner_angle, self._cone_outer_angle) self.lock() self._buffer3d.SetConeAngles(inner, outer, lib.DS3D_IMMEDIATE) self.unlock() def set_cone_outer_gain(self, cone_outer_gain): if self._buffer3d: volume = _db(cone_outer_gain) self.lock() self._buffer3d.SetConeOutsideVolume(volume, lib.DS3D_IMMEDIATE) self.unlock() class DirectSoundDriver(AbstractAudioDriver): def __init__(self): self._dsound = lib.IDirectSound() lib.DirectSoundCreate(None, ctypes.byref(self._dsound), None) # A trick used by mplayer.. use desktop as window handle since it # would be complex to use pyglet window handles (and what to do when # application is audio only?). hwnd = _user32.GetDesktopWindow() self._dsound.SetCooperativeLevel(hwnd, lib.DSSCL_NORMAL) # Create primary buffer with 3D and volume capabilities self._buffer = lib.IDirectSoundBuffer() dsbd = lib.DSBUFFERDESC() dsbd.dwSize = ctypes.sizeof(dsbd) dsbd.dwFlags = (lib.DSBCAPS_CTRL3D | lib.DSBCAPS_CTRLVOLUME | lib.DSBCAPS_PRIMARYBUFFER) self._dsound.CreateSoundBuffer(dsbd, ctypes.byref(self._buffer), None) # Create listener self._listener = lib.IDirectSound3DListener() self._buffer.QueryInterface(lib.IID_IDirectSound3DListener, ctypes.byref(self._listener)) # Create worker thread self.worker = DirectSoundWorker() self.worker.start() def __del__(self): try: if self._buffer: self.delete() except: pass def create_audio_player(self, source_group, player): return DirectSoundAudioPlayer(source_group, player) def delete(self): self.worker.stop() self._buffer.Release() self._buffer = None self._listener.Release() self._listener = None # Listener API def _set_volume(self, volume): self._volume = volume self._buffer.SetVolume(_db(volume)) def _set_position(self, position): self._position = position x, y, z = position self._listener.SetPosition(x, y, -z, lib.DS3D_IMMEDIATE) def _set_forward_orientation(self, orientation): self._forward_orientation = orientation self._set_orientation() def _set_up_orientation(self, orientation): self._up_orientation = orientation self._set_orientation() def _set_orientation(self): x, y, z = self._forward_orientation ux, uy, uz = self._up_orientation self._listener.SetOrientation(x, y, -z, ux, uy, -uz, lib.DS3D_IMMEDIATE) def create_audio_driver(): global driver driver = DirectSoundDriver() return driver # Global driver needed for access to worker thread and _dsound driver = None
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id:$ from pyglet.media import Source, AudioFormat, AudioData import ctypes import os import math class ProceduralSource(Source): def __init__(self, duration, sample_rate=44800, sample_size=16): self._duration = float(duration) self.audio_format = AudioFormat( channels=1, sample_size=sample_size, sample_rate=sample_rate) self._offset = 0 self._bytes_per_sample = sample_size >> 3 self._bytes_per_second = self._bytes_per_sample * sample_rate self._max_offset = int(self._bytes_per_second * self._duration) if self._bytes_per_sample == 2: self._max_offset &= 0xfffffffe def _get_audio_data(self, bytes): bytes = min(bytes, self._max_offset - self._offset) if bytes <= 0: return None timestamp = float(self._offset) / self._bytes_per_second duration = float(bytes) / self._bytes_per_second data = self._generate_data(bytes, self._offset) self._offset += bytes return AudioData(data, bytes, timestamp, duration, []) def _generate_data(self, bytes, offset): '''Generate `bytes` bytes of data. Return data as ctypes array or string. ''' raise NotImplementedError('abstract') def seek(self, timestamp): self._offset = int(timestamp * self._bytes_per_second) # Bound within duration self._offset = min(max(self._offset, 0), self._max_offset) # Align to sample if self._bytes_per_sample == 2: self._offset &= 0xfffffffe class Silence(ProceduralSource): def _generate_data(self, bytes, offset): if self._bytes_per_sample == 1: return '\127' * bytes else: return '\0' * bytes class WhiteNoise(ProceduralSource): def _generate_data(self, bytes, offset): return os.urandom(bytes) class Sine(ProceduralSource): def __init__(self, duration, frequency=440, **kwargs): super(Sine, self).__init__(duration, **kwargs) self.frequency = frequency def _generate_data(self, bytes, offset): if self._bytes_per_sample == 1: start = offset samples = bytes bias = 127 amplitude = 127 data = (ctypes.c_ubyte * samples)() else: start = offset >> 1 samples = bytes >> 1 bias = 0 amplitude = 32767 data = (ctypes.c_short * samples)() step = self.frequency * (math.pi * 2) / self.audio_format.sample_rate for i in range(samples): data[i] = int(math.sin(step * (i + start)) * amplitude + bias) return data class Saw(ProceduralSource): def __init__(self, duration, frequency=440, **kwargs): super(Saw, self).__init__(duration, **kwargs) self.frequency = frequency def _generate_data(self, bytes, offset): # XXX TODO consider offset if self._bytes_per_sample == 1: samples = bytes value = 127 max = 255 min = 0 data = (ctypes.c_ubyte * samples)() else: samples = bytes >> 1 value = 0 max = 32767 min = -32768 data = (ctypes.c_short * samples)() step = (max - min) * 2 * self.frequency / self.audio_format.sample_rate for i in range(samples): value += step if value > max: value = max - (value - max) step = -step if value < min: value = min - (value - min) step = -step data[i] = value return data class Square(ProceduralSource): def __init__(self, duration, frequency=440, **kwargs): super(Square, self).__init__(duration, **kwargs) self.frequency = frequency def _generate_data(self, bytes, offset): # XXX TODO consider offset if self._bytes_per_sample == 1: samples = bytes value = 0 amplitude = 255 data = (ctypes.c_ubyte * samples)() else: samples = bytes >> 1 value = -32768 amplitude = 65535 data = (ctypes.c_short * samples)() period = self.audio_format.sample_rate / self.frequency / 2 count = 0 for i in range(samples): count += 1 if count == period: value = amplitude - value count = 0 data[i] = value return data
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id$ '''Audio and video playback. pyglet can play WAV files, and if AVbin is installed, many other audio and video formats. Playback is handled by the `Player` class, which reads raw data from `Source` objects and provides methods for pausing, seeking, adjusting the volume, and so on. The `Player` class implements the best available audio device (currently, only OpenAL is supported):: player = Player() A `Source` is used to decode arbitrary audio and video files. It is associated with a single player by "queuing" it:: source = load('background_music.mp3') player.queue(source) Use the `Player` to control playback. If the source contains video, the `Source.video_format` attribute will be non-None, and the `Player.texture` attribute will contain the current video image synchronised to the audio. Decoding sounds can be processor-intensive and may introduce latency, particularly for short sounds that must be played quickly, such as bullets or explosions. You can force such sounds to be decoded and retained in memory rather than streamed from disk by wrapping the source in a `StaticSource`:: bullet_sound = StaticSource(load('bullet.wav')) The other advantage of a `StaticSource` is that it can be queued on any number of players, and so played many times simultaneously. pyglet relies on Python's garbage collector to release resources when a player has finished playing a source. In this way some operations that could affect the application performance can be delayed. The player provides a `Player.delete()` method that can be used to release resources immediately. Also an explicit call to `gc.collect()`can be used to collect unused resources. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import atexit import ctypes import heapq import sys import threading import time import pyglet from pyglet.compat import bytes_type, BytesIO _debug = pyglet.options['debug_media'] class MediaException(Exception): pass class MediaFormatException(MediaException): pass class CannotSeekException(MediaException): pass class MediaThread(object): '''A thread that cleanly exits on interpreter shutdown, and provides a sleep method that can be interrupted and a termination method. :Ivariables: `condition` : threading.Condition Lock condition on all instance variables. `stopped` : bool True if `stop` has been called. ''' _threads = set() _threads_lock = threading.Lock() def __init__(self, target=None): self._thread = threading.Thread(target=self._thread_run) self._thread.setDaemon(True) if target is not None: self.run = target self.condition = threading.Condition() self.stopped = False @classmethod def _atexit(cls): cls._threads_lock.acquire() threads = list(cls._threads) cls._threads_lock.release() for thread in threads: thread.stop() def run(self): pass def _thread_run(self): if pyglet.options['debug_trace']: pyglet._install_trace() self._threads_lock.acquire() self._threads.add(self) self._threads_lock.release() self.run() self._threads_lock.acquire() self._threads.remove(self) self._threads_lock.release() def start(self): self._thread.start() def stop(self): '''Stop the thread and wait for it to terminate. The `stop` instance variable is set to ``True`` and the condition is notified. It is the responsibility of the `run` method to check the value of `stop` after each sleep or wait and to return if set. ''' if _debug: print 'MediaThread.stop()' self.condition.acquire() self.stopped = True self.condition.notify() self.condition.release() self._thread.join() def sleep(self, timeout): '''Wait for some amount of time, or until notified. :Parameters: `timeout` : float Time to wait, in seconds. ''' if _debug: print 'MediaThread.sleep(%r)' % timeout self.condition.acquire() self.condition.wait(timeout) self.condition.release() def notify(self): '''Interrupt the current sleep operation. If the thread is currently sleeping, it will be woken immediately, instead of waiting the full duration of the timeout. ''' if _debug: print 'MediaThread.notify()' self.condition.acquire() self.condition.notify() self.condition.release() atexit.register(MediaThread._atexit) class WorkerThread(MediaThread): def __init__(self, target=None): super(WorkerThread, self).__init__(target) self._jobs = [] def run(self): while True: job = self.get_job() if not job: break job() def get_job(self): self.condition.acquire() while self._empty() and not self.stopped: self.condition.wait() if self.stopped: result = None else: result = self._get() self.condition.release() return result def put_job(self, job): self.condition.acquire() self._put(job) self.condition.notify() self.condition.release() def clear_jobs(self): self.condition.acquire() self._clear() self.condition.notify() self.condition.release() def _empty(self): return not self._jobs def _get(self): return self._jobs.pop(0) def _put(self, job): self._jobs.append(job) def _clear(self): del self._jobs[:] class AudioFormat(object): '''Audio details. An instance of this class is provided by sources with audio tracks. You should not modify the fields, as they are used internally to describe the format of data provided by the source. :Ivariables: `channels` : int The number of channels: 1 for mono or 2 for stereo (pyglet does not yet support surround-sound sources). `sample_size` : int Bits per sample; only 8 or 16 are supported. `sample_rate` : int Samples per second (in Hertz). ''' def __init__(self, channels, sample_size, sample_rate): self.channels = channels self.sample_size = sample_size self.sample_rate = sample_rate # Convenience self.bytes_per_sample = (sample_size >> 3) * channels self.bytes_per_second = self.bytes_per_sample * sample_rate def __eq__(self, other): return (self.channels == other.channels and self.sample_size == other.sample_size and self.sample_rate == other.sample_rate) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return '%s(channels=%d, sample_size=%d, sample_rate=%d)' % ( self.__class__.__name__, self.channels, self.sample_size, self.sample_rate) class VideoFormat(object): '''Video details. An instance of this class is provided by sources with a video track. You should not modify the fields. Note that the sample aspect has no relation to the aspect ratio of the video image. For example, a video image of 640x480 with sample aspect 2.0 should be displayed at 1280x480. It is the responsibility of the application to perform this scaling. :Ivariables: `width` : int Width of video image, in pixels. `height` : int Height of video image, in pixels. `sample_aspect` : float Aspect ratio (width over height) of a single video pixel. `frame_rate` : float Frame rate (frames per second) of the video. AVbin 8 or later is required, otherwise the frame rate will be ``None``. **Since:** pyglet 1.2. ''' def __init__(self, width, height, sample_aspect=1.0): self.width = width self.height = height self.sample_aspect = sample_aspect self.frame_rate = None class AudioData(object): '''A single packet of audio data. This class is used internally by pyglet. :Ivariables: `data` : str or ctypes array or pointer Sample data. `length` : int Size of sample data, in bytes. `timestamp` : float Time of the first sample, in seconds. `duration` : float Total data duration, in seconds. `events` : list of MediaEvent List of events contained within this packet. Events are timestamped relative to this audio packet. ''' def __init__(self, data, length, timestamp, duration, events): self.data = data self.length = length self.timestamp = timestamp self.duration = duration self.events = events def consume(self, bytes, audio_format): '''Remove some data from beginning of packet. All events are cleared.''' self.events = () if bytes == self.length: self.data = None self.length = 0 self.timestamp += self.duration self.duration = 0. return elif bytes == 0: return if not isinstance(self.data, str): # XXX Create a string buffer for the whole packet then # chop it up. Could do some pointer arith here and # save a bit of data pushing, but my guess is this is # faster than fudging aruond with ctypes (and easier). data = ctypes.create_string_buffer(self.length) ctypes.memmove(data, self.data, self.length) self.data = data self.data = self.data[bytes:] self.length -= bytes self.duration -= bytes / float(audio_format.bytes_per_second) self.timestamp += bytes / float(audio_format.bytes_per_second) def get_string_data(self): '''Return data as a string. (Python 3: return as bytes)''' if isinstance(self.data, bytes_type): return self.data buf = ctypes.create_string_buffer(self.length) ctypes.memmove(buf, self.data, self.length) return buf.raw class MediaEvent(object): def __init__(self, timestamp, event, *args): # Meaning of timestamp is dependent on context; and not seen by # application. self.timestamp = timestamp self.event = event self.args = args def _sync_dispatch_to_player(self, player): pyglet.app.platform_event_loop.post_event(player, self.event, *self.args) time.sleep(0) # TODO sync with media.dispatch_events def __repr__(self): return '%s(%r, %r, %r)' % (self.__class__.__name__, self.timestamp, self.event, self.args) def __lt__(self, other): return hash(self) < hash(other) class SourceInfo(object): '''Source metadata information. Fields are the empty string or zero if the information is not available. :Ivariables: `title` : str Title `author` : str Author `copyright` : str Copyright statement `comment` : str Comment `album` : str Album name `year` : int Year `track` : int Track number `genre` : str Genre :since: pyglet 1.2 ''' title = '' author = '' copyright = '' comment = '' album = '' year = 0 track = 0 genre = '' class Source(object): '''An audio and/or video source. :Ivariables: `audio_format` : `AudioFormat` Format of the audio in this source, or None if the source is silent. `video_format` : `VideoFormat` Format of the video in this source, or None if there is no video. `info` : `SourceInfo` Source metadata such as title, artist, etc; or None if the information is not available. **Since:** pyglet 1.2 ''' _duration = None audio_format = None video_format = None info = None def _get_duration(self): return self._duration duration = property(lambda self: self._get_duration(), doc='''The length of the source, in seconds. Not all source durations can be determined; in this case the value is None. Read-only. :type: float ''') def play(self): '''Play the source. This is a convenience method which creates a ManagedSoundPlayer for this source and plays it immediately. :rtype: `ManagedSoundPlayer` ''' player = ManagedSoundPlayer() player.queue(self) player.play() return player def get_animation(self): '''Import all video frames into memory as an `Animation`. An empty animation will be returned if the source has no video. Otherwise, the animation will contain all unplayed video frames (the entire source, if it has not been queued on a player). After creating the animation, the source will be at EOS. This method is unsuitable for videos running longer than a few seconds. :since: pyglet 1.1 :rtype: `pyglet.image.Animation` ''' from pyglet.image import Animation, AnimationFrame if not self.video_format: return Animation([]) else: frames = [] last_ts = 0 next_ts = self.get_next_video_timestamp() while next_ts is not None: image = self.get_next_video_frame() if image is not None: delay = next_ts - last_ts frames.append(AnimationFrame(image, delay)) last_ts = next_ts next_ts = self.get_next_video_timestamp() return Animation(frames) def get_next_video_timestamp(self): '''Get the timestamp of the next video frame. :since: pyglet 1.1 :rtype: float :return: The next timestamp, or ``None`` if there are no more video frames. ''' pass def get_next_video_frame(self): '''Get the next video frame. Video frames may share memory: the previous frame may be invalidated or corrupted when this method is called unless the application has made a copy of it. :since: pyglet 1.1 :rtype: `pyglet.image.AbstractImage` :return: The next video frame image, or ``None`` if the video frame could not be decoded or there are no more video frames. ''' pass # Internal methods that SourceGroup calls on the source: def seek(self, timestamp): '''Seek to given timestamp.''' raise CannotSeekException() def _get_queue_source(self): '''Return the `Source` to be used as the queue source for a player. Default implementation returns self.''' return self def get_audio_data(self, bytes): '''Get next packet of audio data. :Parameters: `bytes` : int Maximum number of bytes of data to return. :rtype: `AudioData` :return: Next packet of audio data, or None if there is no (more) data. ''' return None class StreamingSource(Source): '''A source that is decoded as it is being played, and can only be queued once. ''' _is_queued = False is_queued = property(lambda self: self._is_queued, doc='''Determine if this source has been queued on a `Player` yet. Read-only. :type: bool ''') def _get_queue_source(self): '''Return the `Source` to be used as the queue source for a player. Default implementation returns self.''' if self._is_queued: raise MediaException('This source is already queued on a player.') self._is_queued = True return self class StaticSource(Source): '''A source that has been completely decoded in memory. This source can be queued onto multiple players any number of times. ''' def __init__(self, source): '''Construct a `StaticSource` for the data in `source`. :Parameters: `source` : `Source` The source to read and decode audio and video data from. ''' source = source._get_queue_source() if source.video_format: raise NotImplementedError( 'Static sources not supported for video yet.') self.audio_format = source.audio_format if not self.audio_format: return # Arbitrary: number of bytes to request at a time. buffer_size = 1 << 20 # 1 MB # Naive implementation. Driver-specific implementations may override # to load static audio data into device (or at least driver) memory. data = BytesIO() while True: audio_data = source.get_audio_data(buffer_size) if not audio_data: break data.write(audio_data.get_string_data()) self._data = data.getvalue() self._duration = len(self._data) / \ float(self.audio_format.bytes_per_second) def _get_queue_source(self): return StaticMemorySource(self._data, self.audio_format) def get_audio_data(self, bytes): raise RuntimeError('StaticSource cannot be queued.') class StaticMemorySource(StaticSource): '''Helper class for default implementation of `StaticSource`. Do not use directly.''' def __init__(self, data, audio_format): '''Construct a memory source over the given data buffer. ''' self._file = BytesIO(data) self._max_offset = len(data) self.audio_format = audio_format self._duration = len(data) / float(audio_format.bytes_per_second) def seek(self, timestamp): offset = int(timestamp * self.audio_format.bytes_per_second) # Align to sample if self.audio_format.bytes_per_sample == 2: offset &= 0xfffffffe elif self.audio_format.bytes_per_sample == 4: offset &= 0xfffffffc self._file.seek(offset) def get_audio_data(self, bytes): offset = self._file.tell() timestamp = float(offset) / self.audio_format.bytes_per_second # Align to sample size if self.audio_format.bytes_per_sample == 2: bytes &= 0xfffffffe elif self.audio_format.bytes_per_sample == 4: bytes &= 0xfffffffc data = self._file.read(bytes) if not len(data): return None duration = float(len(data)) / self.audio_format.bytes_per_second return AudioData(data, len(data), timestamp, duration, []) class SourceGroup(object): '''Read data from a queue of sources, with support for looping. All sources must share the same audio format. :Ivariables: `audio_format` : `AudioFormat` Required audio format for queued sources. ''' # TODO can sources list go empty? what behaviour (ignore or error)? _advance_after_eos = False _loop = False def __init__(self, audio_format, video_format): self.audio_format = audio_format self.video_format = video_format self.duration = 0. self._timestamp_offset = 0. self._dequeued_durations = [] self._sources = [] def seek(self, time): if self._sources: self._sources[0].seek(time) def queue(self, source): source = source._get_queue_source() assert(source.audio_format == self.audio_format) self._sources.append(source) self.duration += source.duration def has_next(self): return len(self._sources) > 1 def next_source(self, immediate=True): if immediate: self._advance() else: self._advance_after_eos = True #: :deprecated: Use `next_source` instead. next = next_source # old API, worked badly with 2to3 def get_current_source(self): if self._sources: return self._sources[0] def _advance(self): if self._sources: self._timestamp_offset += self._sources[0].duration self._dequeued_durations.insert(0, self._sources[0].duration) old_source = self._sources.pop(0) self.duration -= old_source.duration def _get_loop(self): return self._loop def _set_loop(self, loop): self._loop = loop loop = property(_get_loop, _set_loop, doc='''Loop the current source indefinitely or until `next` is called. Initially False. :type: bool ''') def get_audio_data(self, bytes): '''Get next audio packet. :Parameters: `bytes` : int Hint for preferred size of audio packet; may be ignored. :rtype: `AudioData` :return: Audio data, or None if there is no more data. ''' data = self._sources[0].get_audio_data(bytes) eos = False while not data: eos = True if self._loop and not self._advance_after_eos: self._timestamp_offset += self._sources[0].duration self._dequeued_durations.insert(0, self._sources[0].duration) self._sources[0].seek(0) else: self._advance_after_eos = False # Advance source if there's something to advance to. # Otherwise leave last source paused at EOS. if len(self._sources) > 1: self._advance() else: return None data = self._sources[0].get_audio_data(bytes) # TODO method rename data.timestamp += self._timestamp_offset if eos: if _debug: print 'adding on_eos event to audio data' data.events.append(MediaEvent(0, 'on_eos')) return data def translate_timestamp(self, timestamp): '''Get source-relative timestamp for the audio player's timestamp.''' # XXX if timestamp is None: return None timestamp = timestamp - self._timestamp_offset if timestamp < 0: for duration in self._dequeued_durations[::-1]: timestamp += duration if timestamp > 0: break assert timestamp >= 0, 'Timestamp beyond dequeued source memory' return timestamp def get_next_video_timestamp(self): '''Get the timestamp of the next video frame. :rtype: float :return: The next timestamp, or ``None`` if there are no more video frames. ''' # TODO track current video source independently from audio source for # better prebuffering. timestamp = self._sources[0].get_next_video_timestamp() if timestamp is not None: timestamp += self._timestamp_offset return timestamp def get_next_video_frame(self): '''Get the next video frame. Video frames may share memory: the previous frame may be invalidated or corrupted when this method is called unless the application has made a copy of it. :rtype: `pyglet.image.AbstractImage` :return: The next video frame image, or ``None`` if the video frame could not be decoded or there are no more video frames. ''' return self._sources[0].get_next_video_frame() class AbstractAudioPlayer(object): '''Base class for driver audio players. ''' def __init__(self, source_group, player): '''Create a new audio player. :Parameters: `source_group` : `SourceGroup` Source group to play from. `player` : `Player` Player to receive EOS and video frame sync events. ''' self.source_group = source_group self.player = player def play(self): '''Begin playback.''' raise NotImplementedError('abstract') def stop(self): '''Stop (pause) playback.''' raise NotImplementedError('abstract') def delete(self): '''Stop playing and clean up all resources used by player.''' raise NotImplementedError('abstract') def _play_group(self, audio_players): '''Begin simultaneous playback on a list of audio players.''' # This should be overridden by subclasses for better synchrony. for player in audio_players: player.play() def _stop_group(self, audio_players): '''Stop simultaneous playback on a list of audio players.''' # This should be overridden by subclasses for better synchrony. for player in audio_players: player.play() def clear(self): '''Clear all buffered data and prepare for replacement data. The player should be stopped before calling this method. ''' raise NotImplementedError('abstract') def get_time(self): '''Return approximation of current playback time within current source. Returns ``None`` if the audio player does not know what the playback time is (for example, before any valid audio data has been read). :rtype: float :return: current play cursor time, in seconds. ''' # TODO determine which source within group raise NotImplementedError('abstract') def set_volume(self, volume): '''See `Player.volume`.''' pass def set_position(self, position): '''See `Player.position`.''' pass def set_min_distance(self, min_distance): '''See `Player.min_distance`.''' pass def set_max_distance(self, max_distance): '''See `Player.max_distance`.''' pass def set_pitch(self, pitch): '''See `Player.pitch`.''' pass def set_cone_orientation(self, cone_orientation): '''See `Player.cone_orientation`.''' pass def set_cone_inner_angle(self, cone_inner_angle): '''See `Player.cone_inner_angle`.''' pass def set_cone_outer_angle(self, cone_outer_angle): '''See `Player.cone_outer_angle`.''' pass def set_cone_outer_gain(self, cone_outer_gain): '''See `Player.cone_outer_gain`.''' pass class Player(pyglet.event.EventDispatcher): '''High-level sound and video player. ''' _last_video_timestamp = None _texture = None # Spacialisation attributes, preserved between audio players _volume = 1.0 _min_distance = 1.0 _max_distance = 100000000. _position = (0, 0, 0) _pitch = 1.0 _cone_orientation = (0, 0, 1) _cone_inner_angle = 360. _cone_outer_angle = 360. _cone_outer_gain = 1. #: The player will pause when it reaches the end of the stream. #: #: :deprecated: Use `SourceGroup.advance_after_eos` EOS_PAUSE = 'pause' #: The player will loop the current stream continuosly. #: #: :deprecated: Use `SourceGroup.loop` EOS_LOOP = 'loop' #: The player will move on to the next queued stream when it reaches the #: end of the current source. If there is no source queued, the player #: will pause. #: #: :deprecated: Use `SourceGroup.advance_after_eos` EOS_NEXT = 'next' #: The player will stop entirely; valid only for ManagedSoundPlayer. #: #: :deprecated: Use `SourceGroup.advance_after_eos` EOS_STOP = 'stop' #: :deprecated: _eos_action = EOS_NEXT def __init__(self): # List of queued source groups self._groups = [] self._audio_player = None # Desired play state (not an indication of actual state). self._playing = False self._paused_time = 0.0 def queue(self, source): if isinstance(source, SourceGroup): self._groups.append(source) else: if (self._groups and source.audio_format == self._groups[-1].audio_format and source.video_format == self._groups[-1].video_format): self._groups[-1].queue(source) else: group = SourceGroup(source.audio_format, source.video_format) group.queue(source) self._groups.append(group) self._set_eos_action(self._eos_action) self._set_playing(self._playing) def _set_playing(self, playing): #stopping = self._playing and not playing #starting = not self._playing and playing self._playing = playing source = self.source if playing and source: if not self._audio_player: self._create_audio_player() self._audio_player.play() if source.video_format: if not self._texture: self._create_texture() if self.source.video_format.frame_rate: period = 1. / self.source.video_format.frame_rate else: period = 1. / 30. pyglet.clock.schedule_interval(self.update_texture, period) else: if self._audio_player: self._audio_player.stop() pyglet.clock.unschedule(self.update_texture) def play(self): self._set_playing(True) def pause(self): self._set_playing(False) if self._audio_player: time = self._audio_player.get_time() time = self._groups[0].translate_timestamp(time) if time is not None: self._paused_time = time self._audio_player.stop() def delete(self): self.pause() if self._audio_player: self._audio_player.delete() self._audio_player = None while self._groups: del self._groups[0] def next_source(self): if not self._groups: return group = self._groups[0] if group.has_next(): group.next_source() return if self.source.video_format: self._texture = None pyglet.clock.unschedule(self.update_texture) if self._audio_player: self._audio_player.delete() self._audio_player = None del self._groups[0] if self._groups: self._set_playing(self._playing) return self._set_playing(False) self.dispatch_event('on_player_eos') #: :deprecated: Use `next_source` instead. next = next_source # old API, worked badly with 2to3 def seek(self, time): if _debug: print 'Player.seek(%r)' % time self._paused_time = time self.source.seek(time) if self._audio_player: self._audio_player.clear() if self.source.video_format: self._last_video_timestamp = None self.update_texture(time=time) def _create_audio_player(self): assert not self._audio_player assert self._groups group = self._groups[0] audio_format = group.audio_format if audio_format: audio_driver = get_audio_driver() else: audio_driver = get_silent_audio_driver() self._audio_player = audio_driver.create_audio_player(group, self) _class = self.__class__ def _set(name): private_name = '_' + name value = getattr(self, private_name) if value != getattr(_class, private_name): getattr(self._audio_player, 'set_' + name)(value) _set('volume') _set('min_distance') _set('max_distance') _set('position') _set('pitch') _set('cone_orientation') _set('cone_inner_angle') _set('cone_outer_angle') _set('cone_outer_gain') def _get_source(self): if not self._groups: return None return self._groups[0].get_current_source() source = property(_get_source) playing = property(lambda self: self._playing) def _get_time(self): time = None if self._playing and self._audio_player: time = self._audio_player.get_time() time = self._groups[0].translate_timestamp(time) if time is None: return self._paused_time else: return time time = property(_get_time) def _create_texture(self): video_format = self.source.video_format self._texture = pyglet.image.Texture.create( video_format.width, video_format.height, rectangle=True) self._texture = self._texture.get_transform(flip_y=True) self._texture.anchor_y = 0 def get_texture(self): return self._texture def seek_next_frame(self): '''Step forwards one video frame in the current Source. ''' time = self._groups[0].get_next_video_timestamp() if time is None: return self.seek(time) def update_texture(self, dt=None, time=None): if time is None: time = self._audio_player.get_time() if time is None: return if (self._last_video_timestamp is not None and time <= self._last_video_timestamp): return ts = self._groups[0].get_next_video_timestamp() while ts is not None and ts < time: self._groups[0].get_next_video_frame() # Discard frame ts = self._groups[0].get_next_video_timestamp() if ts is None: self._last_video_timestamp = None return image = self._groups[0].get_next_video_frame() if image is not None: if self._texture is None: self._create_texture() self._texture.blit_into(image, 0, 0, 0) self._last_video_timestamp = ts def _set_eos_action(self, eos_action): ''':deprecated:''' assert eos_action in (self.EOS_NEXT, self.EOS_STOP, self.EOS_PAUSE, self.EOS_LOOP) self._eos_action = eos_action for group in self._groups: group.loop = eos_action == self.EOS_LOOP group.advance_after_eos = eos_action == self.EOS_NEXT eos_action = property(lambda self: self._eos_action, _set_eos_action, doc='''Set the behaviour of the player when it reaches the end of the current source. This must be one of the constants `EOS_NEXT`, `EOS_PAUSE`, `EOS_STOP` or `EOS_LOOP`. :deprecated: Use `SourceGroup.loop` and `SourceGroup.advance_after_eos` :type: str ''') def _player_property(name, doc=None): private_name = '_' + name set_name = 'set_' + name def _player_property_set(self, value): setattr(self, private_name, value) if self._audio_player: getattr(self._audio_player, set_name)(value) def _player_property_get(self): return getattr(self, private_name) return property(_player_property_get, _player_property_set, doc=doc) # TODO docstrings for these... volume = _player_property('volume') min_distance = _player_property('min_distance') max_distance = _player_property('max_distance') position = _player_property('position') pitch = _player_property('pitch') cone_orientation = _player_property('cone_orientation') cone_inner_angle = _player_property('cone_inner_angle') cone_outer_angle = _player_property('cone_outer_angle') cone_outer_gain = _player_property('cone_outer_gain') # Events def on_player_eos(self): '''The player ran out of sources. :event: ''' if _debug: print 'Player.on_player_eos' def on_source_group_eos(self): '''The current source group ran out of data. The default behaviour is to advance to the next source group if possible. :event: ''' self.next_source() if _debug: print 'Player.on_source_group_eos' def on_eos(self): ''' :event: ''' if _debug: print 'Player.on_eos' Player.register_event_type('on_eos') Player.register_event_type('on_player_eos') Player.register_event_type('on_source_group_eos') class ManagedSoundPlayer(Player): ''':deprecated: Use `Player`''' pass class PlayerGroup(object): '''Group of players that can be played and paused simultaneously. :Ivariables: `players` : list of `Player` Players in this group. ''' def __init__(self, players): '''Create a player group for the given set of players. All players in the group must currently not belong to any other group. :Parameters: `players` : Sequence of `Player` Players to add to this group. ''' self.players = list(players) def play(self): '''Begin playing all players in the group simultaneously. ''' audio_players = [p._audio_player \ for p in self.players if p._audio_player] if audio_players: audio_players[0]._play_group(audio_players) for player in self.players: player.play() def pause(self): '''Pause all players in the group simultaneously. ''' audio_players = [p._audio_player \ for p in self.players if p._audio_player] if audio_players: audio_players[0]._stop_group(audio_players) for player in self.players: player.pause() class AbstractAudioDriver(object): def create_audio_player(self, source_group, player): raise NotImplementedError('abstract') def get_listener(self): raise NotImplementedError('abstract') class AbstractListener(object): '''The listener properties for positional audio. You can obtain the singleton instance of this class by calling `AbstractAudioDriver.get_listener`. ''' _volume = 1.0 _position = (0, 0, 0) _forward_orientation = (0, 0, -1) _up_orientation = (0, 1, 0) def _set_volume(self, volume): raise NotImplementedError('abstract') volume = property(lambda self: self._volume, lambda self, volume: self._set_volume(volume), doc='''The master volume for sound playback. All sound volumes are multiplied by this master volume before being played. A value of 0 will silence playback (but still consume resources). The nominal volume is 1.0. :type: float ''') def _set_position(self, position): raise NotImplementedError('abstract') position = property(lambda self: self._position, lambda self, position: self._set_position(position), doc='''The position of the listener in 3D space. The position is given as a tuple of floats (x, y, z). The unit defaults to meters, but can be modified with the listener properties. :type: 3-tuple of float ''') def _set_forward_orientation(self, orientation): raise NotImplementedError('abstract') forward_orientation = property(lambda self: self._forward_orientation, lambda self, o: self._set_forward_orientation(o), doc='''A vector giving the direction the listener is facing. The orientation is given as a tuple of floats (x, y, z), and has no unit. The forward orientation should be orthagonal to the up orientation. :type: 3-tuple of float ''') def _set_up_orientation(self, orientation): raise NotImplementedError('abstract') up_orientation = property(lambda self: self._up_orientation, lambda self, o: self._set_up_orientation(o), doc='''A vector giving the "up" orientation of the listener. The orientation is given as a tuple of floats (x, y, z), and has no unit. The up orientation should be orthagonal to the forward orientation. :type: 3-tuple of float ''') class _LegacyListener(AbstractListener): def _set_volume(self, volume): get_audio_driver().get_listener().volume = volume self._volume = volume def _set_position(self, position): get_audio_driver().get_listener().position = position self._position = position def _set_forward_orientation(self, forward_orientation): get_audio_driver().get_listener().forward_orientation = \ forward_orientation self._forward_orientation = forward_orientation def _set_up_orientation(self, up_orientation): get_audio_driver().get_listener().up_orientation = up_orientation self._up_orientation = up_orientation #: The singleton `AbstractListener` object. #: #: :deprecated: Use `AbstractAudioDriver.get_listener` #: #: :type: `AbstractListener` listener = _LegacyListener() class AbstractSourceLoader(object): def load(self, filename, file): raise NotImplementedError('abstract') class AVbinSourceLoader(AbstractSourceLoader): def load(self, filename, file): import avbin return avbin.AVbinSource(filename, file) class RIFFSourceLoader(AbstractSourceLoader): def load(self, filename, file): import riff return riff.WaveSource(filename, file) def load(filename, file=None, streaming=True): '''Load a source from a file. Currently the `file` argument is not supported; media files must exist as real paths. :Parameters: `filename` : str Filename of the media file to load. `file` : file-like object Not yet supported. `streaming` : bool If False, a `StaticSource` will be returned; otherwise (default) a `StreamingSource` is created. :rtype: `Source` ''' source = get_source_loader().load(filename, file) if not streaming: source = StaticSource(source) return source def get_audio_driver(): global _audio_driver if _audio_driver: return _audio_driver _audio_driver = None for driver_name in pyglet.options['audio']: try: if driver_name == 'pulse': from drivers import pulse _audio_driver = pulse.create_audio_driver() break elif driver_name == 'openal': from drivers import openal _audio_driver = openal.create_audio_driver() break elif driver_name == 'directsound': from drivers import directsound _audio_driver = directsound.create_audio_driver() break elif driver_name == 'silent': _audio_driver = get_silent_audio_driver() break except Exception as exp: if _debug: print 'Error importing driver %s:\n%s' % (driver_name, str(exp)) return _audio_driver def get_silent_audio_driver(): global _silent_audio_driver if not _silent_audio_driver: from drivers import silent _silent_audio_driver = silent.create_audio_driver() return _silent_audio_driver _audio_driver = None _silent_audio_driver = None def get_source_loader(): global _source_loader if _source_loader: return _source_loader try: import avbin _source_loader = AVbinSourceLoader() except ImportError: _source_loader = RIFFSourceLoader() return _source_loader _source_loader = None try: import avbin have_avbin = True except ImportError: have_avbin = False
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Use avbin to decode audio and video media. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import struct import ctypes import threading import time import pyglet from pyglet import gl from pyglet.gl import gl_info from pyglet import image import pyglet.lib from pyglet.media import \ MediaFormatException, StreamingSource, VideoFormat, AudioFormat, \ AudioData, MediaEvent, WorkerThread, SourceInfo from pyglet.compat import asbytes, asbytes_filename if pyglet.compat_platform.startswith('win') and struct.calcsize('P') == 8: av = 'avbin64' else: av = 'avbin' av = pyglet.lib.load_library(av) AVBIN_RESULT_ERROR = -1 AVBIN_RESULT_OK = 0 AVbinResult = ctypes.c_int AVBIN_STREAM_TYPE_UNKNOWN = 0 AVBIN_STREAM_TYPE_VIDEO = 1 AVBIN_STREAM_TYPE_AUDIO = 2 AVbinStreamType = ctypes.c_int AVBIN_SAMPLE_FORMAT_U8 = 0 AVBIN_SAMPLE_FORMAT_S16 = 1 AVBIN_SAMPLE_FORMAT_S24 = 2 AVBIN_SAMPLE_FORMAT_S32 = 3 AVBIN_SAMPLE_FORMAT_FLOAT = 4 AVbinSampleFormat = ctypes.c_int AVBIN_LOG_QUIET = -8 AVBIN_LOG_PANIC = 0 AVBIN_LOG_FATAL = 8 AVBIN_LOG_ERROR = 16 AVBIN_LOG_WARNING = 24 AVBIN_LOG_INFO = 32 AVBIN_LOG_VERBOSE = 40 AVBIN_LOG_DEBUG = 48 AVbinLogLevel = ctypes.c_int AVbinFileP = ctypes.c_void_p AVbinStreamP = ctypes.c_void_p Timestamp = ctypes.c_int64 class AVbinFileInfo(ctypes.Structure): _fields_ = [ ('structure_size', ctypes.c_size_t), ('n_streams', ctypes.c_int), ('start_time', Timestamp), ('duration', Timestamp), ('title', ctypes.c_char * 512), ('author', ctypes.c_char * 512), ('copyright', ctypes.c_char * 512), ('comment', ctypes.c_char * 512), ('album', ctypes.c_char * 512), ('year', ctypes.c_int), ('track', ctypes.c_int), ('genre', ctypes.c_char * 32), ] class _AVbinStreamInfoVideo8(ctypes.Structure): _fields_ = [ ('width', ctypes.c_uint), ('height', ctypes.c_uint), ('sample_aspect_num', ctypes.c_uint), ('sample_aspect_den', ctypes.c_uint), ('frame_rate_num', ctypes.c_uint), ('frame_rate_den', ctypes.c_uint), ] class _AVbinStreamInfoAudio8(ctypes.Structure): _fields_ = [ ('sample_format', ctypes.c_int), ('sample_rate', ctypes.c_uint), ('sample_bits', ctypes.c_uint), ('channels', ctypes.c_uint), ] class _AVbinStreamInfoUnion8(ctypes.Union): _fields_ = [ ('video', _AVbinStreamInfoVideo8), ('audio', _AVbinStreamInfoAudio8), ] class AVbinStreamInfo8(ctypes.Structure): _fields_ = [ ('structure_size', ctypes.c_size_t), ('type', ctypes.c_int), ('u', _AVbinStreamInfoUnion8) ] class AVbinPacket(ctypes.Structure): _fields_ = [ ('structure_size', ctypes.c_size_t), ('timestamp', Timestamp), ('stream_index', ctypes.c_int), ('data', ctypes.POINTER(ctypes.c_uint8)), ('size', ctypes.c_size_t), ] AVbinLogCallback = ctypes.CFUNCTYPE(None, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p) av.avbin_get_version.restype = ctypes.c_int av.avbin_get_ffmpeg_revision.restype = ctypes.c_int av.avbin_get_audio_buffer_size.restype = ctypes.c_size_t av.avbin_have_feature.restype = ctypes.c_int av.avbin_have_feature.argtypes = [ctypes.c_char_p] av.avbin_init.restype = AVbinResult av.avbin_set_log_level.restype = AVbinResult av.avbin_set_log_level.argtypes = [AVbinLogLevel] av.avbin_set_log_callback.argtypes = [AVbinLogCallback] av.avbin_open_filename.restype = AVbinFileP av.avbin_open_filename.argtypes = [ctypes.c_char_p] av.avbin_close_file.argtypes = [AVbinFileP] av.avbin_seek_file.argtypes = [AVbinFileP, Timestamp] av.avbin_file_info.argtypes = [AVbinFileP, ctypes.POINTER(AVbinFileInfo)] av.avbin_stream_info.argtypes = [AVbinFileP, ctypes.c_int, ctypes.POINTER(AVbinStreamInfo8)] av.avbin_open_stream.restype = ctypes.c_void_p av.avbin_open_stream.argtypes = [AVbinFileP, ctypes.c_int] av.avbin_close_stream.argtypes = [AVbinStreamP] av.avbin_read.argtypes = [AVbinFileP, ctypes.POINTER(AVbinPacket)] av.avbin_read.restype = AVbinResult av.avbin_decode_audio.restype = ctypes.c_int av.avbin_decode_audio.argtypes = [AVbinStreamP, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)] av.avbin_decode_video.restype = ctypes.c_int av.avbin_decode_video.argtypes = [AVbinStreamP, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p] if True: # XXX lock all avbin calls. not clear from ffmpeg documentation if this # is necessary. leaving it on while debugging to rule out the possiblity # of a problem. def synchronize(func, lock): def f(*args): lock.acquire() result = func(*args) lock.release() return result return f _avbin_lock = threading.Lock() for name in dir(av): if name.startswith('avbin_'): setattr(av, name, synchronize(getattr(av, name), _avbin_lock)) def get_version(): return av.avbin_get_version() class AVbinException(MediaFormatException): pass def timestamp_from_avbin(timestamp): return float(timestamp) / 1000000 def timestamp_to_avbin(timestamp): return int(timestamp * 1000000) class VideoPacket(object): _next_id = 0 def __init__(self, packet): self.timestamp = timestamp_from_avbin(packet.timestamp) self.data = (ctypes.c_uint8 * packet.size)() self.size = packet.size ctypes.memmove(self.data, packet.data, self.size) # Decoded image. 0 == not decoded yet; None == Error or discarded self.image = 0 self.id = self._next_id self.__class__._next_id += 1 class AVbinSource(StreamingSource): def __init__(self, filename, file=None): if file is not None: raise NotImplementedError('Loading from file stream is not supported') self._file = av.avbin_open_filename(asbytes_filename(filename)) if not self._file: raise AVbinException('Could not open "%s"' % filename) self._video_stream = None self._video_stream_index = -1 self._audio_stream = None self._audio_stream_index = -1 file_info = AVbinFileInfo() file_info.structure_size = ctypes.sizeof(file_info) av.avbin_file_info(self._file, ctypes.byref(file_info)) self._duration = timestamp_from_avbin(file_info.duration) self.info = SourceInfo() self.info.title = file_info.title self.info.author = file_info.author self.info.copyright = file_info.copyright self.info.comment = file_info.comment self.info.album = file_info.album self.info.year = file_info.year self.info.track = file_info.track self.info.genre = file_info.genre # Pick the first video and audio streams found, ignore others. for i in range(file_info.n_streams): info = AVbinStreamInfo8() info.structure_size = ctypes.sizeof(info) av.avbin_stream_info(self._file, i, info) if (info.type == AVBIN_STREAM_TYPE_VIDEO and not self._video_stream): stream = av.avbin_open_stream(self._file, i) if not stream: continue self.video_format = VideoFormat( width=info.u.video.width, height=info.u.video.height) if info.u.video.sample_aspect_num != 0: self.video_format.sample_aspect = ( float(info.u.video.sample_aspect_num) / info.u.video.sample_aspect_den) if _have_frame_rate: self.video_format.frame_rate = ( float(info.u.video.frame_rate_num) / info.u.video.frame_rate_den) self._video_stream = stream self._video_stream_index = i elif (info.type == AVBIN_STREAM_TYPE_AUDIO and info.u.audio.sample_bits in (8, 16) and info.u.audio.channels in (1, 2) and not self._audio_stream): stream = av.avbin_open_stream(self._file, i) if not stream: continue self.audio_format = AudioFormat( channels=info.u.audio.channels, sample_size=info.u.audio.sample_bits, sample_rate=info.u.audio.sample_rate) self._audio_stream = stream self._audio_stream_index = i self._packet = AVbinPacket() self._packet.structure_size = ctypes.sizeof(self._packet) self._packet.stream_index = -1 self._events = [] # Timestamp of last video packet added to decoder queue. self._video_timestamp = 0 self._buffered_audio_data = [] if self.audio_format: self._audio_buffer = \ (ctypes.c_uint8 * av.avbin_get_audio_buffer_size())() if self.video_format: self._video_packets = [] self._decode_thread = WorkerThread() self._decode_thread.start() self._condition = threading.Condition() def __del__(self): if _debug: print 'del avbin source' try: if self._video_stream: av.avbin_close_stream(self._video_stream) if self._audio_stream: av.avbin_close_stream(self._audio_stream) av.avbin_close_file(self._file) except: pass # XXX TODO call this / add to source api def delete(self): if self.video_format: self._decode_thread.stop() def seek(self, timestamp): if _debug: print 'AVbin seek', timestamp av.avbin_seek_file(self._file, timestamp_to_avbin(timestamp)) self._audio_packet_size = 0 del self._events[:] del self._buffered_audio_data[:] if self.video_format: self._video_timestamp = 0 self._condition.acquire() for packet in self._video_packets: packet.image = None self._condition.notify() self._condition.release() del self._video_packets[:] self._decode_thread.clear_jobs() def _get_packet(self): # Read a packet into self._packet. Returns True if OK, False if no # more packets are in stream. return av.avbin_read(self._file, self._packet) == AVBIN_RESULT_OK def _process_packet(self): # Returns (packet_type, packet), where packet_type = 'video' or # 'audio'; and packet is VideoPacket or AudioData. In either case, # packet is buffered or queued for decoding; no further action is # necessary. Returns (None, None) if packet was neither type. if self._packet.stream_index == self._video_stream_index: if self._packet.timestamp < 0: # XXX TODO # AVbin needs hack to decode timestamp for B frames in # some containers (OGG?). See # http://www.dranger.com/ffmpeg/tutorial05.html # For now we just drop these frames. return None, None video_packet = VideoPacket(self._packet) if _debug: print 'Created and queued frame %d (%f)' % \ (video_packet.id, video_packet.timestamp) self._video_timestamp = max(self._video_timestamp, video_packet.timestamp) self._video_packets.append(video_packet) self._decode_thread.put_job( lambda: self._decode_video_packet(video_packet)) return 'video', video_packet elif self._packet.stream_index == self._audio_stream_index: audio_data = self._decode_audio_packet() if audio_data: if _debug: print 'Got an audio packet at', audio_data.timestamp self._buffered_audio_data.append(audio_data) return 'audio', audio_data return None, None def get_audio_data(self, bytes): try: audio_data = self._buffered_audio_data.pop(0) audio_data_timeend = audio_data.timestamp + audio_data.duration except IndexError: audio_data = None audio_data_timeend = self._video_timestamp + 1 if _debug: print 'get_audio_data' have_video_work = False # Keep reading packets until we have an audio packet and all the # associated video packets have been enqueued on the decoder thread. while not audio_data or ( self._video_stream and self._video_timestamp < audio_data_timeend): if not self._get_packet(): break packet_type, packet = self._process_packet() if packet_type == 'video': have_video_work = True elif not audio_data and packet_type == 'audio': audio_data = self._buffered_audio_data.pop(0) if _debug: print 'Got requested audio packet at', audio_data.timestamp audio_data_timeend = audio_data.timestamp + audio_data.duration if have_video_work: # Give decoder thread a chance to run before we return this audio # data. time.sleep(0) if not audio_data: if _debug: print 'get_audio_data returning None' return None while self._events and self._events[0].timestamp <= audio_data_timeend: event = self._events.pop(0) if event.timestamp >= audio_data.timestamp: event.timestamp -= audio_data.timestamp audio_data.events.append(event) if _debug: print 'get_audio_data returning ts %f with events' % \ audio_data.timestamp, audio_data.events print 'remaining events are', self._events return audio_data def _decode_audio_packet(self): packet = self._packet size_out = ctypes.c_int(len(self._audio_buffer)) while True: audio_packet_ptr = ctypes.cast(packet.data, ctypes.c_void_p) audio_packet_size = packet.size used = av.avbin_decode_audio(self._audio_stream, audio_packet_ptr, audio_packet_size, self._audio_buffer, size_out) if used < 0: self._audio_packet_size = 0 break audio_packet_ptr.value += used audio_packet_size -= used if size_out.value <= 0: continue # XXX how did this ever work? replaced with copy below # buffer = ctypes.string_at(self._audio_buffer, size_out) # XXX to actually copy the data.. but it never used to crash, so # maybe I'm missing something buffer = ctypes.create_string_buffer(size_out.value) ctypes.memmove(buffer, self._audio_buffer, len(buffer)) buffer = buffer.raw duration = float(len(buffer)) / self.audio_format.bytes_per_second self._audio_packet_timestamp = \ timestamp = timestamp_from_avbin(packet.timestamp) return AudioData(buffer, len(buffer), timestamp, duration, []) def _decode_video_packet(self, packet): width = self.video_format.width height = self.video_format.height pitch = width * 3 buffer = (ctypes.c_uint8 * (pitch * height))() result = av.avbin_decode_video(self._video_stream, packet.data, packet.size, buffer) if result < 0: image_data = None else: image_data = image.ImageData(width, height, 'RGB', buffer, pitch) packet.image = image_data # Notify get_next_video_frame() that another one is ready. self._condition.acquire() self._condition.notify() self._condition.release() def _ensure_video_packets(self): '''Process packets until a video packet has been queued (and begun decoding). Return False if EOS. ''' if not self._video_packets: if _debug: print 'No video packets...' # Read ahead until we have another video packet self._get_packet() packet_type, _ = self._process_packet() while packet_type and packet_type != 'video': self._get_packet() packet_type, _ = self._process_packet() if not packet_type: return False if _debug: print 'Queued packet', _ return True def get_next_video_timestamp(self): if not self.video_format: return if self._ensure_video_packets(): if _debug: print 'Next video timestamp is', self._video_packets[0].timestamp return self._video_packets[0].timestamp def get_next_video_frame(self): if not self.video_format: return if self._ensure_video_packets(): packet = self._video_packets.pop(0) if _debug: print 'Waiting for', packet # Block until decoding is complete self._condition.acquire() while packet.image == 0: self._condition.wait() self._condition.release() if _debug: print 'Returning', packet return packet.image av.avbin_init() if pyglet.options['debug_media']: _debug = True av.avbin_set_log_level(AVBIN_LOG_DEBUG) else: _debug = False av.avbin_set_log_level(AVBIN_LOG_QUIET) _have_frame_rate = av.avbin_have_feature(asbytes('frame_rate'))
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # $Id:$ '''Minimal Windows COM interface. Allows pyglet to use COM interfaces on Windows without comtypes. Unlike comtypes, this module does not provide property interfaces, read typelibs, nice-ify return values or permit Python implementations of COM interfaces. We don't need anything that sophisticated to work with DirectX. All interfaces should derive from IUnknown (defined in this module). The Python COM interfaces are actually pointers to the implementation (take note when translating methods that take an interface as argument). Interfaces can define methods:: class IDirectSound8(com.IUnknown): _methods_ = [ ('CreateSoundBuffer', com.STDMETHOD()), ('GetCaps', com.STDMETHOD(LPDSCAPS)), ... ] Only use STDMETHOD or METHOD for the method types (not ordinary ctypes function types). The 'this' pointer is bound automatically... e.g., call:: device = IDirectSound8() DirectSoundCreate8(None, ctypes.byref(device), None) caps = DSCAPS() device.GetCaps(caps) Because STDMETHODs use HRESULT as the return type, there is no need to check the return value. Don't forget to manually manage memory... call Release() when you're done with an interface. ''' import ctypes import sys if sys.platform != 'win32': raise ImportError('pyglet.com requires a Windows build of Python') class GUID(ctypes.Structure): _fields_ = [ ('Data1', ctypes.c_ulong), ('Data2', ctypes.c_ushort), ('Data3', ctypes.c_ushort), ('Data4', ctypes.c_ubyte * 8) ] def __init__(self, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8): self.Data1 = l self.Data2 = w1 self.Data3 = w2 self.Data4[:] = (b1, b2, b3, b4, b5, b6, b7, b8) def __repr__(self): b1, b2, b3, b4, b5, b6, b7, b8 = self.Data4 return 'GUID(%x, %x, %x, %x, %x, %x, %x, %x, %x, %x, %x)' % ( self.Data1, self.Data2, self.Data3, b1, b2, b3, b4, b5, b6, b7, b8) LPGUID = ctypes.POINTER(GUID) IID = GUID REFIID = ctypes.POINTER(IID) class METHOD(object): '''COM method.''' def __init__(self, restype, *args): self.restype = restype self.argtypes = args def get_field(self): return ctypes.WINFUNCTYPE(self.restype, *self.argtypes) class STDMETHOD(METHOD): '''COM method with HRESULT return value.''' def __init__(self, *args): super(STDMETHOD, self).__init__(ctypes.HRESULT, *args) class COMMethodInstance(object): '''Binds a COM interface method.''' def __init__(self, name, i, method): self.name = name self.i = i self.method = method def __get__(self, obj, tp): if obj is not None: return lambda *args: \ self.method.get_field()(self.i, self.name)(obj, *args) raise AttributeError() class COMInterface(ctypes.Structure): '''Dummy struct to serve as the type of all COM pointers.''' _fields_ = [ ('lpVtbl', ctypes.c_void_p), ] class InterfaceMetaclass(type(ctypes.POINTER(COMInterface))): '''Creates COM interface pointers.''' def __new__(cls, name, bases, dct): methods = [] for base in bases[::-1]: methods.extend(base.__dict__.get('_methods_', ())) methods.extend(dct.get('_methods_', ())) for i, (n, method) in enumerate(methods): dct[n] = COMMethodInstance(n, i, method) dct['_type_'] = COMInterface return super(InterfaceMetaclass, cls).__new__(cls, name, bases, dct) class Interface(ctypes.POINTER(COMInterface)): '''Base COM interface pointer.''' __metaclass__ = InterfaceMetaclass class IUnknown(Interface): _methods_ = [ ('QueryInterface', STDMETHOD(REFIID, ctypes.c_void_p)), ('AddRef', METHOD(ctypes.c_int)), ('Release', METHOD(ctypes.c_int)) ]
Python
# Uses the HID API introduced in Mac OS X version 10.5 # http://developer.apple.com/library/mac/#technotes/tn2007/tn2187.html import sys __LP64__ = (sys.maxint > 2**32) from pyglet.libs.darwin.cocoapy import * # Load iokit framework iokit = cdll.LoadLibrary(util.find_library('IOKit')) # IOKit constants from # /System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDKeys.h kIOHIDOptionsTypeNone = 0x00 kIOHIDOptionsTypeSeizeDevice = 0x01 kIOHIDElementTypeInput_Misc = 1 kIOHIDElementTypeInput_Button = 2 kIOHIDElementTypeInput_Axis = 3 kIOHIDElementTypeInput_ScanCodes = 4 kIOHIDElementTypeOutput = 129 kIOHIDElementTypeFeature = 257 kIOHIDElementTypeCollection = 513 # /System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDUsageTables.h kHIDPage_GenericDesktop = 0x01 kHIDPage_Consumer = 0x0C kHIDUsage_GD_SystemSleep = 0x82 kHIDUsage_GD_SystemWakeUp = 0x83 kHIDUsage_GD_SystemAppMenu = 0x86 kHIDUsage_GD_SystemMenu = 0x89 kHIDUsage_GD_SystemMenuRight = 0x8A kHIDUsage_GD_SystemMenuLeft = 0x8B kHIDUsage_GD_SystemMenuUp = 0x8C kHIDUsage_GD_SystemMenuDown = 0x8D kHIDUsage_Csmr_Menu = 0x40 kHIDUsage_Csmr_FastForward = 0xB3 kHIDUsage_Csmr_Rewind = 0xB4 kHIDUsage_Csmr_Eject = 0xB8 kHIDUsage_Csmr_Mute = 0xE2 kHIDUsage_Csmr_VolumeIncrement = 0xE9 kHIDUsage_Csmr_VolumeDecrement = 0xEA IOReturn = c_int # IOReturn.h IOOptionBits = c_uint32 # IOTypes.h # IOHIDKeys.h IOHIDElementType = c_int IOHIDElementCollectionType = c_int if __LP64__: IOHIDElementCookie = c_uint32 else: IOHIDElementCookie = c_void_p iokit.IOHIDDeviceClose.restype = IOReturn iokit.IOHIDDeviceClose.argtypes = [c_void_p, IOOptionBits] iokit.IOHIDDeviceConformsTo.restype = c_ubyte iokit.IOHIDDeviceConformsTo.argtypes = [c_void_p, c_uint32, c_uint32] iokit.IOHIDDeviceCopyMatchingElements.restype = c_void_p iokit.IOHIDDeviceCopyMatchingElements.argtypes = [c_void_p, c_void_p, IOOptionBits] iokit.IOHIDDeviceGetProperty.restype = c_void_p iokit.IOHIDDeviceGetProperty.argtypes = [c_void_p, c_void_p] iokit.IOHIDDeviceGetTypeID.restype = CFTypeID iokit.IOHIDDeviceGetTypeID.argtypes = [] iokit.IOHIDDeviceGetValue.restype = IOReturn iokit.IOHIDDeviceGetValue.argtypes = [c_void_p, c_void_p, c_void_p] iokit.IOHIDDeviceOpen.restype = IOReturn iokit.IOHIDDeviceOpen.argtypes = [c_void_p, IOOptionBits] iokit.IOHIDDeviceRegisterInputValueCallback.restype = None iokit.IOHIDDeviceRegisterInputValueCallback.argtypes = [c_void_p, c_void_p, c_void_p] iokit.IOHIDDeviceRegisterRemovalCallback.restype = None iokit.IOHIDDeviceRegisterRemovalCallback.argtypes = [c_void_p, c_void_p, c_void_p] iokit.IOHIDDeviceScheduleWithRunLoop.restype = None iokit.IOHIDDeviceScheduleWithRunLoop.argtypes = [c_void_p, c_void_p, c_void_p] iokit.IOHIDDeviceUnscheduleFromRunLoop.restype = None iokit.IOHIDDeviceUnscheduleFromRunLoop.argtypes = [c_void_p, c_void_p, c_void_p] iokit.IOHIDElementGetCollectionType.restype = IOHIDElementCollectionType iokit.IOHIDElementGetCollectionType.argtypes = [c_void_p] iokit.IOHIDElementGetCookie.restype = IOHIDElementCookie iokit.IOHIDElementGetCookie.argtypes = [c_void_p] iokit.IOHIDElementGetLogicalMax.restype = CFIndex iokit.IOHIDElementGetLogicalMax.argtypes = [c_void_p] iokit.IOHIDElementGetLogicalMin.restype = CFIndex iokit.IOHIDElementGetLogicalMin.argtypes = [c_void_p] iokit.IOHIDElementGetName.restype = c_void_p iokit.IOHIDElementGetName.argtypes = [c_void_p] iokit.IOHIDElementGetPhysicalMax.restype = CFIndex iokit.IOHIDElementGetPhysicalMax.argtypes = [c_void_p] iokit.IOHIDElementGetPhysicalMin.restype = CFIndex iokit.IOHIDElementGetPhysicalMin.argtypes = [c_void_p] iokit.IOHIDElementGetReportCount.restype = c_uint32 iokit.IOHIDElementGetReportCount.argtypes = [c_void_p] iokit.IOHIDElementGetReportID.restype = c_uint32 iokit.IOHIDElementGetReportID.argtypes = [c_void_p] iokit.IOHIDElementGetReportSize.restype = c_uint32 iokit.IOHIDElementGetReportSize.argtypes = [c_void_p] iokit.IOHIDElementGetType.restype = IOHIDElementType iokit.IOHIDElementGetType.argtypes = [c_void_p] iokit.IOHIDElementGetTypeID.restype = CFTypeID iokit.IOHIDElementGetTypeID.argtypes = [] iokit.IOHIDElementGetUnit.restype = c_uint32 iokit.IOHIDElementGetUnit.argtypes = [c_void_p] iokit.IOHIDElementGetUnitExponent.restype = c_uint32 iokit.IOHIDElementGetUnitExponent.argtypes = [c_void_p] iokit.IOHIDElementGetUsage.restype = c_uint32 iokit.IOHIDElementGetUsage.argtypes = [c_void_p] iokit.IOHIDElementGetUsagePage.restype = c_uint32 iokit.IOHIDElementGetUsagePage.argtypes = [c_void_p] iokit.IOHIDElementHasNullState.restype = c_bool iokit.IOHIDElementHasNullState.argtypes = [c_void_p] iokit.IOHIDElementHasPreferredState.restype = c_bool iokit.IOHIDElementHasPreferredState.argtypes = [c_void_p] iokit.IOHIDElementIsArray.restype = c_bool iokit.IOHIDElementIsArray.argtypes = [c_void_p] iokit.IOHIDElementIsNonLinear.restype = c_bool iokit.IOHIDElementIsNonLinear.argtypes = [c_void_p] iokit.IOHIDElementIsRelative.restype = c_bool iokit.IOHIDElementIsRelative.argtypes = [c_void_p] iokit.IOHIDElementIsVirtual.restype = c_bool iokit.IOHIDElementIsVirtual.argtypes = [c_void_p] iokit.IOHIDElementIsWrapping.restype = c_bool iokit.IOHIDElementIsWrapping.argtypes = [c_void_p] iokit.IOHIDManagerCreate.restype = c_void_p iokit.IOHIDManagerCreate.argtypes = [CFAllocatorRef, IOOptionBits] iokit.IOHIDManagerCopyDevices.restype = c_void_p iokit.IOHIDManagerCopyDevices.argtypes = [c_void_p] iokit.IOHIDManagerGetTypeID.restype = CFTypeID iokit.IOHIDManagerGetTypeID.argtypes = [] iokit.IOHIDManagerRegisterDeviceMatchingCallback.restype = None iokit.IOHIDManagerRegisterDeviceMatchingCallback.argtypes = [c_void_p, c_void_p, c_void_p] iokit.IOHIDManagerScheduleWithRunLoop.restype = c_void_p iokit.IOHIDManagerScheduleWithRunLoop.argtypes = [c_void_p, c_void_p, c_void_p] iokit.IOHIDManagerSetDeviceMatching.restype = None iokit.IOHIDManagerSetDeviceMatching.argtypes = [c_void_p, c_void_p] iokit.IOHIDValueGetElement.restype = c_void_p iokit.IOHIDValueGetElement.argtypes = [c_void_p] iokit.IOHIDValueGetIntegerValue.restype = CFIndex iokit.IOHIDValueGetIntegerValue.argtypes = [c_void_p] iokit.IOHIDValueGetLength.restype = CFIndex iokit.IOHIDValueGetLength.argtypes = [c_void_p] iokit.IOHIDValueGetTimeStamp.restype = c_uint64 iokit.IOHIDValueGetTimeStamp.argtypes = [c_void_p] iokit.IOHIDValueGetTypeID.restype = CFTypeID iokit.IOHIDValueGetTypeID.argtypes = [] # Callback function types HIDManagerCallback = CFUNCTYPE(None, c_void_p, c_int, c_void_p, c_void_p) HIDDeviceCallback = CFUNCTYPE(None, c_void_p, c_int, c_void_p) HIDDeviceValueCallback = CFUNCTYPE(None, c_void_p, c_int, c_void_p, c_void_p) ###################################################################### # HID Class Wrappers # Lookup tables cache python objects for the devices and elements so that # we can avoid creating multiple wrapper objects for the same device. _device_lookup = {} # IOHIDDeviceRef to python HIDDevice object _element_lookup = {} # IOHIDElementRef to python HIDDeviceElement object class HIDValue: def __init__(self, valueRef): # Check that this is a valid IOHIDValue. assert(valueRef) assert(cf.CFGetTypeID(valueRef) == iokit.IOHIDValueGetTypeID()) self.valueRef = valueRef self.timestamp = iokit.IOHIDValueGetTimeStamp(valueRef) self.length = iokit.IOHIDValueGetLength(valueRef) if self.length <= 4: self.intvalue = iokit.IOHIDValueGetIntegerValue(valueRef) else: # Values may be byte data rather than integers. # e.g. the PS3 controller has a 39-byte HIDValue element. # We currently do not try to handle these cases. self.intvalue = None elementRef = c_void_p(iokit.IOHIDValueGetElement(valueRef)) self.element = HIDDeviceElement.get_element(elementRef) class HIDDevice: @classmethod def get_device(cls, deviceRef): # deviceRef is a c_void_p pointing to an IOHIDDeviceRef if deviceRef.value in _device_lookup: return _device_lookup[deviceRef.value] else: device = HIDDevice(deviceRef) return device def __init__(self, deviceRef): # Check that we've got a valid IOHIDDevice. assert(deviceRef) assert(cf.CFGetTypeID(deviceRef) == iokit.IOHIDDeviceGetTypeID()) _device_lookup[deviceRef.value] = self self.deviceRef = deviceRef # Set attributes from device properties. self.transport = self.get_property("Transport") self.vendorID = self.get_property("VendorID") self.vendorIDSource = self.get_property("VendorIDSource") self.productID = self.get_property("ProductID") self.versionNumber = self.get_property("VersionNumber") self.manufacturer = self.get_property("Manufacturer") self.product = self.get_property("Product") self.serialNumber = self.get_property("SerialNumber") # always returns None; apple bug? self.locationID = self.get_property("LocationID") self.primaryUsage = self.get_property("PrimaryUsage") self.primaryUsagePage = self.get_property("PrimaryUsagePage") # Populate self.elements with our device elements. self.get_elements() # Set up callback functions. self.value_observers = set() self.removal_observers = set() self.register_removal_callback() self.register_input_value_callback() def dump_info(self): for x in ('manufacturer', 'product', 'transport', 'vendorID', 'vendorIDSource', 'productID', 'versionNumber', 'serialNumber', 'locationID', 'primaryUsage', 'primaryUsagePage'): value = getattr(self, x) print x + ":", value def unique_identifier(self): # Since we can't rely on the serial number, create our own identifier. # Can use this to find devices when they are plugged back in. return (self.manufacturer, self.product, self.vendorID, self.productID, self.versionNumber, self.primaryUsage, self.primaryUsagePage) def get_property(self, name): cfname = CFSTR(name) cfvalue = c_void_p(iokit.IOHIDDeviceGetProperty(self.deviceRef, cfname)) cf.CFRelease(cfname) return cftype_to_value(cfvalue) def open(self, exclusive_mode=False): if exclusive_mode: options = kIOHIDOptionsTypeSeizeDevice else: options = kIOHIDOptionsTypeNone return bool(iokit.IOHIDDeviceOpen(self.deviceRef, options)) def close(self): return bool(iokit.IOHIDDeviceClose(self.deviceRef, kIOHIDOptionsTypeNone)) def schedule_with_run_loop(self): iokit.IOHIDDeviceScheduleWithRunLoop( self.deviceRef, c_void_p(cf.CFRunLoopGetCurrent()), kCFRunLoopDefaultMode) def unschedule_from_run_loop(self): iokit.IOHIDDeviceUnscheduleFromRunLoop( self.deviceRef, c_void_p(cf.CFRunLoopGetCurrent()), kCFRunLoopDefaultMode) def get_elements(self): cfarray = c_void_p(iokit.IOHIDDeviceCopyMatchingElements(self.deviceRef, None, 0)) self.elements = cfarray_to_list(cfarray) cf.CFRelease(cfarray) # Page and usage IDs are from the HID usage tables located at # http://www.usb.org/developers/devclass_docs/Hut1_12.pdf def conforms_to(self, page, usage): return bool(iokit.IOHIDDeviceConformsTo(self.deviceRef, page, usage)) def is_pointer(self): return self.conforms_to(0x01, 0x01) def is_mouse(self): return self.conforms_to(0x01, 0x02) def is_joystick(self): return self.conforms_to(0x01, 0x04) def is_gamepad(self): return self.conforms_to(0x01, 0x05) def is_keyboard(self): return self.conforms_to(0x01, 0x06) def is_keypad(self): return self.conforms_to(0x01, 0x07) def is_multi_axis(self): return self.conforms_to(0x01, 0x08) def py_removal_callback(self, context, result, sender): self = _device_lookup[sender] # avoid wonky python context issues # Dispatch removal message to all observers. for x in self.removal_observers: if hasattr(x, 'device_removed'): x.device_removed(self) # Remove self from device lookup table. del _device_lookup[sender] # Remove device elements from lookup table. for key, value in _element_lookup.items(): if value in self.elements: del _element_lookup[key] def register_removal_callback(self): self.removal_callback = HIDDeviceCallback(self.py_removal_callback) iokit.IOHIDDeviceRegisterRemovalCallback( self.deviceRef, self.removal_callback, None) def add_removal_observer(self, observer): self.removal_observers.add(observer) def py_value_callback(self, context, result, sender, value): v = HIDValue(c_void_p(value)) # Dispatch value changed message to all observers. for x in self.value_observers: if hasattr(x, 'device_value_changed'): x.device_value_changed(self, v) def register_input_value_callback(self): self.value_callback = HIDDeviceValueCallback(self.py_value_callback) iokit.IOHIDDeviceRegisterInputValueCallback( self.deviceRef, self.value_callback, None) def add_value_observer(self, observer): self.value_observers.add(observer) def get_value(self, element): # If the device is not open, then returns None valueRef = c_void_p() iokit.IOHIDDeviceGetValue(self.deviceRef, element.elementRef, byref(valueRef)) if valueRef: return HIDValue(valueRef) else: return None class HIDDeviceElement: @classmethod def get_element(cls, elementRef): # elementRef is a c_void_p pointing to an IOHIDDeviceElementRef if elementRef.value in _element_lookup: return _element_lookup[elementRef.value] else: element = HIDDeviceElement(elementRef) return element def __init__(self, elementRef): # Check that we've been passed a valid IOHIDElement. assert(elementRef) assert(cf.CFGetTypeID(elementRef) == iokit.IOHIDElementGetTypeID()) _element_lookup[elementRef.value] = self self.elementRef = elementRef # Set element properties as attributes. self.cookie = iokit.IOHIDElementGetCookie(elementRef) self.type = iokit.IOHIDElementGetType(elementRef) if self.type == kIOHIDElementTypeCollection: self.collectionType = iokit.IOHIDElementGetCollectionType(elementRef) else: self.collectionType = None self.usagePage = iokit.IOHIDElementGetUsagePage(elementRef) self.usage = iokit.IOHIDElementGetUsage(elementRef) self.isVirtual = bool(iokit.IOHIDElementIsVirtual(elementRef)) self.isRelative = bool(iokit.IOHIDElementIsRelative(elementRef)) self.isWrapping = bool(iokit.IOHIDElementIsWrapping(elementRef)) self.isArray = bool(iokit.IOHIDElementIsArray(elementRef)) self.isNonLinear = bool(iokit.IOHIDElementIsNonLinear(elementRef)) self.hasPreferredState = bool(iokit.IOHIDElementHasPreferredState(elementRef)) self.hasNullState = bool(iokit.IOHIDElementHasNullState(elementRef)) self.name = cftype_to_value(iokit.IOHIDElementGetName(elementRef)) self.reportID = iokit.IOHIDElementGetReportID(elementRef) self.reportSize = iokit.IOHIDElementGetReportSize(elementRef) self.reportCount = iokit.IOHIDElementGetReportCount(elementRef) self.unit = iokit.IOHIDElementGetUnit(elementRef) self.unitExponent = iokit.IOHIDElementGetUnitExponent(elementRef) self.logicalMin = iokit.IOHIDElementGetLogicalMin(elementRef) self.logicalMax = iokit.IOHIDElementGetLogicalMax(elementRef) self.physicalMin = iokit.IOHIDElementGetPhysicalMin(elementRef) self.physicalMax = iokit.IOHIDElementGetPhysicalMax(elementRef) class HIDManager: def __init__(self): # Create the HID Manager. self.managerRef = c_void_p(iokit.IOHIDManagerCreate(None, kIOHIDOptionsTypeNone)) assert(self.managerRef) assert cf.CFGetTypeID(self.managerRef) == iokit.IOHIDManagerGetTypeID() self.schedule_with_run_loop() self.matching_observers = set() self.register_matching_callback() self.get_devices() def get_devices(self): # Tell manager that we are willing to match *any* device. # (Alternatively, we could restrict by device usage, or usage page.) iokit.IOHIDManagerSetDeviceMatching(self.managerRef, None) # Copy the device set and convert it to python. cfset = c_void_p(iokit.IOHIDManagerCopyDevices(self.managerRef)) self.devices = cfset_to_set(cfset) cf.CFRelease(cfset) def open(self): iokit.IOHIDManagerOpen(self.managerRef, kIOHIDOptionsTypeNone) def close(self): iokit.IOHIDManagerClose(self.managerRef, kIOHIDOptionsTypeNone) def schedule_with_run_loop(self): iokit.IOHIDManagerScheduleWithRunLoop( self.managerRef, c_void_p(cf.CFRunLoopGetCurrent()), kCFRunLoopDefaultMode) def unschedule_from_run_loop(self): iokit.IOHIDManagerUnscheduleFromRunLoop( self.managerRef, c_void_p(cf.CFRunLoopGetCurrent()), kCFRunLoopDefaultMode) def py_matching_callback(self, context, result, sender, device): d = HIDDevice.get_device(c_void_p(device)) if d not in self.devices: self.devices.add(d) for x in self.matching_observers: if hasattr(x, 'device_discovered'): x.device_discovered(d) def register_matching_callback(self): self.matching_callback = HIDManagerCallback(self.py_matching_callback) iokit.IOHIDManagerRegisterDeviceMatchingCallback( self.managerRef, self.matching_callback, None) ###################################################################### # Add conversion methods for IOHIDDevices and IOHIDDeviceElements # to the list of known types used by cftype_to_value. known_cftypes[iokit.IOHIDDeviceGetTypeID()] = HIDDevice.get_device known_cftypes[iokit.IOHIDElementGetTypeID()] = HIDDeviceElement.get_element ###################################################################### # Pyglet interface to HID from base import Device, Control, AbsoluteAxis, RelativeAxis, Button from base import Joystick, AppleRemote from base import DeviceExclusiveException _axis_names = { (0x01, 0x30): 'x', (0x01, 0x31): 'y', (0x01, 0x32): 'z', (0x01, 0x33): 'rx', (0x01, 0x34): 'ry', (0x01, 0x35): 'rz', (0x01, 0x38): 'wheel', (0x01, 0x39): 'hat', } _button_names = { (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemSleep): 'sleep', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemWakeUp): 'wakeup', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemAppMenu): 'menu', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenu): 'select', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenuRight): 'right', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenuLeft): 'left', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenuUp): 'up', (kHIDPage_GenericDesktop, kHIDUsage_GD_SystemMenuDown): 'down', (kHIDPage_Consumer, kHIDUsage_Csmr_FastForward): 'right_hold', (kHIDPage_Consumer, kHIDUsage_Csmr_Rewind): 'left_hold', (kHIDPage_Consumer, kHIDUsage_Csmr_Menu): 'menu_hold', (0xff01, 0x23): 'select_hold', (kHIDPage_Consumer, kHIDUsage_Csmr_Eject): 'eject', (kHIDPage_Consumer, kHIDUsage_Csmr_Mute): 'mute', (kHIDPage_Consumer, kHIDUsage_Csmr_VolumeIncrement): 'volume_up', (kHIDPage_Consumer, kHIDUsage_Csmr_VolumeDecrement): 'volume_down' } class PygletDevice(Device): def __init__(self, display, device, manager): super(PygletDevice, self).__init__(display, device.product) self.device = device self.device_identifier = self.device.unique_identifier() self.device.add_value_observer(self) self.device.add_removal_observer(self) manager.matching_observers.add(self) self._create_controls() self._is_open = False self._is_exclusive = False def open(self, window=None, exclusive=False): super(PygletDevice, self).open(window, exclusive) self.device.open(exclusive) self.device.schedule_with_run_loop() self._is_open = True self._is_exclusive = exclusive self._set_initial_control_values() def close(self): super(PygletDevice, self).close() self.device.close() self._is_open = False def get_controls(self): return self._controls.values() def device_removed(self, hid_device): # Called by device when it is unplugged. # Set device to None, but Keep self._controls around # in case device is plugged back in. self.device = None def device_discovered(self, hid_device): # Called by HID manager when new device is found. # If our device was disconnected, reconnect when it is plugged back in. if not self.device and self.device_identifier == hid_device.unique_identifier(): self.device = hid_device self.device.add_value_observer(self) self.device.add_removal_observer(self) # Don't need to recreate controls since this is same device. # They are indexed by cookie, which is constant. if self._is_open: self.device.open(self._is_exclusive) self.device.schedule_with_run_loop() def device_value_changed(self, hid_device, hid_value): # Called by device when input value changes. control = self._controls[hid_value.element.cookie] control._set_value(hid_value.intvalue) def _create_controls(self): self._controls = {} for element in self.device.elements: raw_name = element.name or '0x%x:%x' % (element.usagePage, element.usage) if element.type in (kIOHIDElementTypeInput_Misc, kIOHIDElementTypeInput_Axis): name = _axis_names.get((element.usagePage, element.usage)) if element.isRelative: control = RelativeAxis(name, raw_name) else: control = AbsoluteAxis(name, element.logicalMin, element.logicalMax, raw_name) elif element.type == kIOHIDElementTypeInput_Button: name = _button_names.get((element.usagePage, element.usage)) control = Button(name, raw_name) else: continue control._cookie = element.cookie self._controls[control._cookie] = control def _set_initial_control_values(self): # Must be called AFTER the device has been opened. for element in self.device.elements: if element.cookie in self._controls: control = self._controls[element.cookie] hid_value = self.device.get_value(element) if hid_value: control._set_value(hid_value.intvalue) ###################################################################### _manager = HIDManager() def get_devices(display=None): return [ PygletDevice(display, device, _manager) for device in _manager.devices ] def get_joysticks(display=None): return [ Joystick(PygletDevice(display, device, _manager)) for device in _manager.devices if device.is_joystick() or device.is_gamepad() or device.is_multi_axis() ] def get_apple_remote(display=None): for device in _manager.devices: if device.product == 'Apple IR': return AppleRemote(PygletDevice(display, device, _manager))
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes import pyglet from pyglet.input.base import \ Device, DeviceException, DeviceOpenException, \ Control, Button, RelativeAxis, AbsoluteAxis from pyglet.libs.x11 import xlib from pyglet.compat import asstr try: from pyglet.libs.x11 import xinput as xi _have_xinput = True except: _have_xinput = False def ptr_add(ptr, offset): address = ctypes.addressof(ptr.contents) + offset return ctypes.pointer(type(ptr.contents).from_address(address)) class DeviceResponder(object): def _key_press(self, e): pass def _key_release(self, e): pass def _button_press(self, e): pass def _button_release(self, e): pass def _motion(self, e): pass def _proximity_in(self, e): pass def _proximity_out(self, e): pass class XInputDevice(DeviceResponder, Device): def __init__(self, display, device_info): super(XInputDevice, self).__init__(display, asstr(device_info.name)) self._device_id = device_info.id self._device = None # Read device info self.buttons = [] self.keys = [] self.axes = [] ptr = device_info.inputclassinfo for i in range(device_info.num_classes): cp = ctypes.cast(ptr, ctypes.POINTER(xi.XAnyClassInfo)) cls_class = getattr(cp.contents, 'class') if cls_class == xi.KeyClass: cp = ctypes.cast(ptr, ctypes.POINTER(xi.XKeyInfo)) self.min_keycode = cp.contents.min_keycode num_keys = cp.contents.num_keys for i in range(num_keys): self.keys.append(Button('key%d' % i)) elif cls_class == xi.ButtonClass: cp = ctypes.cast(ptr, ctypes.POINTER(xi.XButtonInfo)) num_buttons = cp.contents.num_buttons for i in range(num_buttons): self.buttons.append(Button('button%d' % i)) elif cls_class == xi.ValuatorClass: cp = ctypes.cast(ptr, ctypes.POINTER(xi.XValuatorInfo)) num_axes = cp.contents.num_axes mode = cp.contents.mode axes = ctypes.cast(cp.contents.axes, ctypes.POINTER(xi.XAxisInfo)) for i in range(num_axes): axis = axes[i] if mode == xi.Absolute: self.axes.append(AbsoluteAxis('axis%d' % i, min=axis.min_value, max=axis.max_value)) elif mode == xi.Relative: self.axes.append(RelativeAxis('axis%d' % i)) cls = cp.contents ptr = ptr_add(ptr, cls.length) self.controls = self.buttons + self.keys + self.axes # Can't detect proximity class event without opening device. Just # assume there is the possibility of a control if there are any axes. if self.axes: self.proximity_control = Button('proximity') self.controls.append(self.proximity_control) else: self.proximity_control = None def get_controls(self): return self.controls def open(self, window=None, exclusive=False): # Checks for is_open and raises if already open. # TODO allow opening on multiple windows. super(XInputDevice, self).open(window, exclusive) if window is None: self.is_open = False raise DeviceOpenException('XInput devices require a window') if window.display._display != self.display._display: self.is_open = False raise DeviceOpenException('Window and device displays differ') if exclusive: self.is_open = False raise DeviceOpenException('Cannot open XInput device exclusive') self._device = xi.XOpenDevice(self.display._display, self._device_id) if not self._device: self.is_open = False raise DeviceOpenException('Cannot open device') self._install_events(window) def close(self): super(XInputDevice, self).close() if not self._device: return # TODO: uninstall events xi.XCloseDevice(self.display._display, self._device) def _install_events(self, window): dispatcher = XInputWindowEventDispatcher.get_dispatcher(window) dispatcher.open_device(self._device_id, self._device, self) # DeviceResponder interface def _key_press(self, e): self.keys[e.keycode - self.min_keycode]._set_value(True) def _key_release(self, e): self.keys[e.keycode - self.min_keycode]._set_value(False) def _button_press(self, e): self.buttons[e.button]._set_value(True) def _button_release(self, e): self.buttons[e.button]._set_value(False) def _motion(self, e): for i in range(e.axes_count): self.axes[i]._set_value(e.axis_data[i]) def _proximity_in(self, e): if self.proximity_control: self.proximity_control._set_value(True) def _proximity_out(self, e): if self.proximity_control: self.proximity_control._set_value(False) class XInputWindowEventDispatcher(object): def __init__(self, window): self.window = window self._responders = {} @staticmethod def get_dispatcher(window): try: dispatcher = window.__xinput_window_event_dispatcher except AttributeError: dispatcher = window.__xinput_window_event_dispatcher = \ XInputWindowEventDispatcher(window) return dispatcher def set_responder(self, device_id, responder): self._responders[device_id] = responder def remove_responder(self, device_id): del self._responders[device_id] def open_device(self, device_id, device, responder): self.set_responder(device_id, responder) device = device.contents if not device.num_classes: return # Bind matching extended window events to bound instance methods # on this object. # # This is inspired by test.c of xinput package by Frederic # Lepied available at x.org. # # In C, this stuff is normally handled by the macro DeviceKeyPress and # friends. Since we don't have access to those macros here, we do it # this way. events = [] def add(class_info, event, handler): _type = class_info.event_type_base + event _class = device_id << 8 | _type events.append(_class) self.window._event_handlers[_type] = handler for i in range(device.num_classes): class_info = device.classes[i] if class_info.input_class == xi.KeyClass: add(class_info, xi._deviceKeyPress, self._event_xinput_key_press) add(class_info, xi._deviceKeyRelease, self._event_xinput_key_release) elif class_info.input_class == xi.ButtonClass: add(class_info, xi._deviceButtonPress, self._event_xinput_button_press) add(class_info, xi._deviceButtonRelease, self._event_xinput_button_release) elif class_info.input_class == xi.ValuatorClass: add(class_info, xi._deviceMotionNotify, self._event_xinput_motion) elif class_info.input_class == xi.ProximityClass: add(class_info, xi._proximityIn, self._event_xinput_proximity_in) add(class_info, xi._proximityOut, self._event_xinput_proximity_out) elif class_info.input_class == xi.FeedbackClass: pass elif class_info.input_class == xi.FocusClass: pass elif class_info.input_class == xi.OtherClass: pass array = (xi.XEventClass * len(events))(*events) xi.XSelectExtensionEvent(self.window._x_display, self.window._window, array, len(array)) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_key_press(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceKeyEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._key_press(e) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_key_release(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceKeyEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._key_release(e) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_button_press(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceButtonEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._button_press(e) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_button_release(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceButtonEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._button_release(e) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_motion(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceMotionEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._motion(e) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_proximity_in(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XProximityNotifyEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._proximity_in(e) @pyglet.window.xlib.XlibEventHandler(-1) def _event_xinput_proximity_out(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XProximityNotifyEvent)).contents device = self._responders.get(e.deviceid) if device is not None: device._proximity_out(e) def _check_extension(display): major_opcode = ctypes.c_int() first_event = ctypes.c_int() first_error = ctypes.c_int() xlib.XQueryExtension(display._display, 'XInputExtension', ctypes.byref(major_opcode), ctypes.byref(first_event), ctypes.byref(first_error)) return bool(major_opcode.value) def get_devices(display=None): if display is None: display = pyglet.canvas.get_display() if not _have_xinput or not _check_extension(display): return [] devices = [] count = ctypes.c_int(0) device_list = xi.XListInputDevices(display._display, count) for i in range(count.value): device_info = device_list[i] devices.append(XInputDevice(display, device_info)) xi.XFreeDeviceList(device_list) return devices
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes import pyglet from pyglet.input.base import Tablet, TabletCanvas, TabletCursor from pyglet.window.carbon import CarbonEventHandler from pyglet.libs.darwin import * from pyglet.libs.darwin import _oscheck class CarbonTablet(Tablet): name = 'OS X System Tablet' def open(self, window): return CarbonTabletCanvas(window) _carbon_tablet = CarbonTablet() class CarbonTabletCanvas(TabletCanvas): def __init__(self, window): super(CarbonTabletCanvas, self).__init__(window) for funcname in dir(self): func = getattr(self, funcname) if hasattr(func, '_platform_event'): window._install_event_handler(func) self._cursors = {} self._cursor = None def close(self): # XXX TODO remove event handlers. pass def _get_cursor(self, proximity_rec): key = (proximity_rec.vendorID, proximity_rec.tabletID, proximity_rec.pointerID, proximity_rec.deviceID, proximity_rec.systemTabletID, proximity_rec.vendorPointerType, proximity_rec.pointerSerialNumber, proximity_rec.uniqueID, proximity_rec.pointerType) if key in self._cursors: cursor = self._cursors[key] else: self._cursors[key] = cursor = \ CarbonTabletCursor(proximity_rec.pointerType) self._cursor = cursor return cursor @CarbonEventHandler(kEventClassTablet, kEventTabletProximity) @CarbonEventHandler(kEventClassTablet, kEventTabletPoint) @CarbonEventHandler(kEventClassMouse, kEventMouseDragged) @CarbonEventHandler(kEventClassMouse, kEventMouseDown) @CarbonEventHandler(kEventClassMouse, kEventMouseUp) @CarbonEventHandler(kEventClassMouse, kEventMouseMoved) def _tablet_event(self, next_handler, ev, data): '''Process tablet event and return True if some event was processed. Return True if no tablet event found. ''' event_type = ctypes.c_uint32() r = carbon.GetEventParameter(ev, kEventParamTabletEventType, typeUInt32, None, ctypes.sizeof(event_type), None, ctypes.byref(event_type)) if r != noErr: return False if event_type.value == kEventTabletProximity: proximity_rec = TabletProximityRec() _oscheck( carbon.GetEventParameter(ev, kEventParamTabletProximityRec, typeTabletProximityRec, None, ctypes.sizeof(proximity_rec), None, ctypes.byref(proximity_rec)) ) cursor = self._get_cursor(proximity_rec) if proximity_rec.enterProximity: self.dispatch_event('on_enter', cursor) else: self.dispatch_event('on_leave', cursor) elif event_type.value == kEventTabletPoint: point_rec = TabletPointRec() _oscheck( carbon.GetEventParameter(ev, kEventParamTabletPointRec, typeTabletPointRec, None, ctypes.sizeof(point_rec), None, ctypes.byref(point_rec)) ) #x = point_rec.absX #y = point_rec.absY x, y = self.window._get_mouse_position(ev) pressure = point_rec.pressure / float(0xffff) #point_rec.tiltX, #point_rec.tiltY, #point_rec.rotation, #point_rec.tangentialPressure, self.dispatch_event('on_motion', self._cursor, x, y, pressure, 0., 0.) carbon.CallNextEventHandler(next_handler, ev) return noErr class CarbonTabletCursor(TabletCursor): def __init__(self, cursor_type): # First approximation based on my results from a Wacom consumer # tablet if cursor_type == 1: name = 'Stylus' elif cursor_type == 3: name = 'Eraser' super(CarbonTabletCursor, self).__init__(name) def get_tablets(display=None): return [_carbon_tablet]
Python
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Interface classes for `pyglet.input`. :since: pyglet 1.2 ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import sys from pyglet.event import EventDispatcher _is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc class DeviceException(Exception): pass class DeviceOpenException(DeviceException): pass class DeviceExclusiveException(DeviceException): pass class Device(object): '''Input device. :Ivariables: `display` : `Display` Display this device is connected to. `name` : str Name of the device, as described by the device firmware. `manufacturer` : str Name of the device manufacturer, or ``None`` if the information is not available. ''' def __init__(self, display, name): self.display = display self.name = name self.manufacturer = None # TODO: make private self.is_open = False def open(self, window=None, exclusive=False): '''Open the device to begin receiving input from it. :Parameters: `window` : Window Optional window to associate with the device. The behaviour of this parameter is device and operating system dependant. It can usually be omitted for most devices. `exclusive` : bool If ``True`` the device will be opened exclusively so that no other application can use it. The method will raise `DeviceExclusiveException` if the device cannot be opened this way (for example, because another application has already opened it). ''' if self.is_open: raise DeviceOpenException('Device is already open.') self.is_open = True def close(self): '''Close the device. ''' self.is_open = False def get_controls(self): '''Get a list of controls provided by the device. :rtype: list of `Control` ''' raise NotImplementedError('abstract') def __repr__(self): return '%s(name=%s)' % (self.__class__.__name__, self.name) class Control(EventDispatcher): '''Single value input provided by a device. A control's value can be queried when the device is open. Event handlers can be attached to the control to be called when the value changes. The `min` and `max` properties are provided as advertised by the device; in some cases the control's value will be outside this range. :Ivariables: `name` : str Name of the control, or ``None`` if unknown `raw_name` : str Unmodified name of the control, as presented by the operating system; or ``None`` if unknown. `inverted` : bool If ``True``, the value reported is actually inverted from what the device reported; usually this is to provide consistency across operating systems. ''' _value = None def __init__(self, name, raw_name=None): self.name = name self.raw_name = raw_name self.inverted = False def _get_value(self): return self._value def _set_value(self, value): if value == self._value: return self._value = value self.dispatch_event('on_change', value) value = property(_get_value, doc='''Current value of the control. The range of the value is device-dependent; for absolute controls the range is given by ``min`` and ``max`` (however the value may exceed this range); for relative controls the range is undefined. :type: float''') def __repr__(self): if self.name: return '%s(name=%s, raw_name=%s)' % ( self.__class__.__name__, self.name, self.raw_name) else: return '%s(raw_name=%s)' % (self.__class__.__name__, self.raw_name) if _is_epydoc: def on_change(self, value): '''The value changed. :Parameters: `value` : float Current value of the control. :event: ''' Control.register_event_type('on_change') class RelativeAxis(Control): '''An axis whose value represents a relative change from the previous value. ''' #: Name of the horizontal axis control X = 'x' #: Name of the vertical axis control Y = 'y' #: Name of the Z axis control. Z = 'z' #: Name of the rotational-X axis control RX = 'rx' #: Name of the rotational-Y axis control RY = 'ry' #: Name of the rotational-Z axis control RZ = 'rz' #: Name of the scroll wheel control WHEEL = 'wheel' def _get_value(self): return self._value def _set_value(self, value): self._value = value self.dispatch_event('on_change', value) value = property(_get_value) class AbsoluteAxis(Control): '''An axis whose value represents a physical measurement from the device. The value is advertised to range over ``min`` and ``max``. :Ivariables: `min` : float Minimum advertised value. `max` : float Maximum advertised value. ''' #: Name of the horizontal axis control X = 'x' #: Name of the vertical axis control Y = 'y' #: Name of the Z axis control. Z = 'z' #: Name of the rotational-X axis control RX = 'rx' #: Name of the rotational-Y axis control RY = 'ry' #: Name of the rotational-Z axis control RZ = 'rz' #: Name of the hat (POV) control, when a single control enumerates all of #: the hat's positions. HAT = 'hat' #: Name of the hat's (POV's) horizontal control, when the hat position is #: described by two orthogonal controls. HAT_X = 'hat_x' #: Name of the hat's (POV's) vertical control, when the hat position is #: described by two orthogonal controls. HAT_Y = 'hat_y' def __init__(self, name, min, max, raw_name=None): super(AbsoluteAxis, self).__init__(name, raw_name) self.min = min self.max = max class Button(Control): '''A control whose value is boolean. ''' def _get_value(self): return bool(self._value) def _set_value(self, value): if value == self._value: return self._value = value self.dispatch_event('on_change', bool(value)) if value: self.dispatch_event('on_press') else: self.dispatch_event('on_release') value = property(_get_value) if _is_epydoc: def on_press(self): '''The button was pressed. :event: ''' def on_release(self): '''The button was released. :event: ''' Button.register_event_type('on_press') Button.register_event_type('on_release') class Joystick(EventDispatcher): '''High-level interface for joystick-like devices. This includes analogue and digital joysticks, gamepads, game controllers, and possibly even steering wheels and other input devices. There is unfortunately no way to distinguish between these different device types. To use a joystick, first call `open`, then in your game loop examine the values of `x`, `y`, and so on. These values are normalized to the range [-1.0, 1.0]. To receive events when the value of an axis changes, attach an on_joyaxis_motion event handler to the joystick. The `Joystick` instance, axis name, and current value are passed as parameters to this event. To handle button events, you should attach on_joybutton_press and on_joy_button_release event handlers to the joystick. Both the `Joystick` instance and the index of the changed button are passed as parameters to these events. Alternately, you may attach event handlers to each individual button in `button_controls` to receive on_press or on_release events. To use the hat switch, attach an on_joyhat_motion event handler to the joystick. The handler will be called with both the hat_x and hat_y values whenever the value of the hat switch changes. The device name can be queried to get the name of the joystick. :Ivariables: `device` : `Device` The underlying device used by this joystick interface. `x` : float Current X (horizontal) value ranging from -1.0 (left) to 1.0 (right). `y` : float Current y (vertical) value ranging from -1.0 (top) to 1.0 (bottom). `z` : float Current Z value ranging from -1.0 to 1.0. On joysticks the Z value is usually the throttle control. On game controllers the Z value is usually the secondary thumb vertical axis. `rx` : float Current rotational X value ranging from -1.0 to 1.0. `ry` : float Current rotational Y value ranging from -1.0 to 1.0. `rz` : float Current rotational Z value ranging from -1.0 to 1.0. On joysticks the RZ value is usually the twist of the stick. On game controllers the RZ value is usually the secondary thumb horizontal axis. `hat_x` : int Current hat (POV) horizontal position; one of -1 (left), 0 (centered) or 1 (right). `hat_y` : int Current hat (POV) vertical position; one of -1 (bottom), 0 (centered) or 1 (top). `buttons` : list of bool List of boolean values representing current states of the buttons. These are in order, so that button 1 has value at ``buttons[0]``, and so on. `x_control` : `AbsoluteAxis` Underlying control for `x` value, or ``None`` if not available. `y_control` : `AbsoluteAxis` Underlying control for `y` value, or ``None`` if not available. `z_control` : `AbsoluteAxis` Underlying control for `z` value, or ``None`` if not available. `rx_control` : `AbsoluteAxis` Underlying control for `rx` value, or ``None`` if not available. `ry_control` : `AbsoluteAxis` Underlying control for `ry` value, or ``None`` if not available. `rz_control` : `AbsoluteAxis` Underlying control for `rz` value, or ``None`` if not available. `hat_x_control` : `AbsoluteAxis` Underlying control for `hat_x` value, or ``None`` if not available. `hat_y_control` : `AbsoluteAxis` Underlying control for `hat_y` value, or ``None`` if not available. `button_controls` : list of `Button` Underlying controls for `buttons` values. ''' def __init__(self, device): self.device = device self.x = 0 self.y = 0 self.z = 0 self.rx = 0 self.ry = 0 self.rz = 0 self.hat_x = 0 self.hat_y = 0 self.buttons = [] self.x_control = None self.y_control = None self.z_control = None self.rx_control = None self.ry_control = None self.rz_control = None self.hat_x_control = None self.hat_y_control = None self.button_controls = [] def add_axis(control): name = control.name scale = 2.0 / (control.max - control.min) bias = -1.0 - control.min * scale if control.inverted: scale = -scale bias = -bias setattr(self, name + '_control', control) @control.event def on_change(value): normalized_value = value * scale + bias setattr(self, name, normalized_value) self.dispatch_event('on_joyaxis_motion', self, name, normalized_value) def add_button(control): i = len(self.buttons) self.buttons.append(False) self.button_controls.append(control) @control.event def on_change(value): self.buttons[i] = value @control.event def on_press(): self.dispatch_event('on_joybutton_press', self, i) @control.event def on_release(): self.dispatch_event('on_joybutton_release', self, i) def add_hat(control): # 8-directional hat encoded as a single control (Windows/Mac) self.hat_x_control = control self.hat_y_control = control @control.event def on_change(value): if value & 0xffff == 0xffff: self.hat_x = self.hat_y = 0 else: if control.max > 8: # DirectInput: scale value value //= 0xfff if 0 <= value < 8: self.hat_x, self.hat_y = ( ( 0, 1), ( 1, 1), ( 1, 0), ( 1, -1), ( 0, -1), (-1, -1), (-1, 0), (-1, 1), )[value] else: # Out of range self.hat_x = self.hat_y = 0 self.dispatch_event('on_joyhat_motion', self, self.hat_x, self.hat_y) for control in device.get_controls(): if isinstance(control, AbsoluteAxis): if control.name in ('x', 'y', 'z', 'rx', 'ry', 'rz', 'hat_x', 'hat_y'): add_axis(control) elif control.name == 'hat': add_hat(control) elif isinstance(control, Button): add_button(control) def open(self, window=None, exclusive=False): '''Open the joystick device. See `Device.open`. ''' self.device.open(window, exclusive) def close(self): '''Close the joystick device. See `Device.close`. ''' self.device.close() def on_joyaxis_motion(self, joystick, axis, value): '''The value of a joystick axis changed. :Parameters: `joystick` : `Joystick` The joystick device whose axis changed. `axis` : string The name of the axis that changed. `value` : float The current value of the axis, normalized to [-1, 1]. ''' def on_joybutton_press(self, joystick, button): '''A button on the joystick was pressed. :Parameters: `joystick` : `Joystick` The joystick device whose button was pressed. `button` : int The index (in `button_controls`) of the button that was pressed. ''' def on_joybutton_release(self, joystick, button): '''A button on the joystick was released. :Parameters: `joystick` : `Joystick` The joystick device whose button was released. `button` : int The index (in `button_controls`) of the button that was released. ''' def on_joyhat_motion(self, joystick, hat_x, hat_y): '''The value of the joystick hat switch changed. :Parameters: `joystick` : `Joystick` The joystick device whose hat control changed. `hat_x` : int Current hat (POV) horizontal position; one of -1 (left), 0 (centered) or 1 (right). `hat_y` : int Current hat (POV) vertical position; one of -1 (bottom), 0 (centered) or 1 (top). ''' Joystick.register_event_type('on_joyaxis_motion') Joystick.register_event_type('on_joybutton_press') Joystick.register_event_type('on_joybutton_release') Joystick.register_event_type('on_joyhat_motion') class AppleRemote(EventDispatcher): '''High-level interface for Apple remote control. This interface provides access to the 6 button controls on the remote. Pressing and holding certain buttons on the remote is interpreted as a separate control. :Ivariables: `device` : `Device` The underlying device used by this interface. `left_control` : `Button` Button control for the left (prev) button. `left_hold_control` : `Button` Button control for holding the left button (rewind). `right_control` : `Button` Button control for the right (next) button. `right_hold_control` : `Button` Button control for holding the right button (fast forward). `up_control` : `Button` Button control for the up (volume increase) button. `down_control` : `Button` Button control for the down (volume decrease) button. `select_control` : `Button` Button control for the select (play/pause) button. `select_hold_control` : `Button` Button control for holding the select button. `menu_control` : `Button` Button control for the menu button. `menu_hold_control` : `Button` Button control for holding the menu button. ''' def __init__(self, device): def add_button(control): setattr(self, control.name + '_control', control) @control.event def on_press(): self.dispatch_event('on_button_press', control.name) @control.event def on_release(): self.dispatch_event('on_button_release', control.name) self.device = device for control in device.get_controls(): if control.name in ('left', 'left_hold', 'right', 'right_hold', 'up', 'down', 'menu', 'select', 'menu_hold', 'select_hold'): add_button(control) def open(self, window=None, exclusive=False): '''Open the device. See `Device.open`. ''' self.device.open(window, exclusive) def close(self): '''Close the device. See `Device.close`. ''' self.device.close() def on_button_press(self, button): """A button on the remote was pressed. Only the 'up' and 'down' buttons will generate an event when the button is first pressed. All other buttons on the remote will wait until the button is released and then send both the press and release events at the same time. :Parameters: `button` : unicode The name of the button that was pressed. The valid names are 'up', 'down', 'left', 'right', 'left_hold', 'right_hold', 'menu', 'menu_hold', 'select', and 'select_hold' :event: """ def on_button_release(self, button): """A button on the remote was released. The 'select_hold' and 'menu_hold' button release events are sent immediately after the corresponding press events regardless of whether or not the user has released the button. :Parameters: `button` : unicode The name of the button that was released. The valid names are 'up', 'down', 'left', 'right', 'left_hold', 'right_hold', 'menu', 'menu_hold', 'select', and 'select_hold' :event: """ AppleRemote.register_event_type('on_button_press') AppleRemote.register_event_type('on_button_release') class Tablet(object): '''High-level interface to tablet devices. Unlike other devices, tablets must be opened for a specific window, and cannot be opened exclusively. The `open` method returns a `TabletCanvas` object, which supports the events provided by the tablet. Currently only one tablet device can be used, though it can be opened on multiple windows. If more than one tablet is connected, the behaviour is undefined. ''' def open(self, window): '''Open a tablet device for a window. :Parameters: `window` : `Window` The window on which the tablet will be used. :rtype: `TabletCanvas` ''' raise NotImplementedError('abstract') class TabletCanvas(EventDispatcher): '''Event dispatcher for tablets. Use `Tablet.open` to obtain this object for a particular tablet device and window. Events may be generated even if the tablet stylus is outside of the window; this is operating-system dependent. The events each provide the `TabletCursor` that was used to generate the event; for example, to distinguish between a stylus and an eraser. Only one cursor can be used at a time, otherwise the results are undefined. :Ivariables: `window` : Window The window on which this tablet was opened. ''' # OS X: Active window receives tablet events only when cursor is in window # Windows: Active window receives all tablet events # # Note that this means enter/leave pairs are not always consistent (normal # usage). def __init__(self, window): self.window = window def close(self): '''Close the tablet device for this window. ''' raise NotImplementedError('abstract') if _is_epydoc: def on_enter(self, cursor): '''A cursor entered the proximity of the window. The cursor may be hovering above the tablet surface, but outside of the window bounds, or it may have entered the window bounds. Note that you cannot rely on `on_enter` and `on_leave` events to be generated in pairs; some events may be lost if the cursor was out of the window bounds at the time. :Parameters: `cursor` : `TabletCursor` The cursor that entered proximity. :event: ''' def on_leave(self, cursor): '''A cursor left the proximity of the window. The cursor may have moved too high above the tablet surface to be detected, or it may have left the bounds of the window. Note that you cannot rely on `on_enter` and `on_leave` events to be generated in pairs; some events may be lost if the cursor was out of the window bounds at the time. :Parameters: `cursor` : `TabletCursor` The cursor that left proximity. :event: ''' def on_motion(self, cursor, x, y, pressure): '''The cursor moved on the tablet surface. If `pressure` is 0, then the cursor is actually hovering above the tablet surface, not in contact. :Parameters: `cursor` : `TabletCursor` The cursor that moved. `x` : int The X position of the cursor, in window coordinates. `y` : int The Y position of the cursor, in window coordinates. `pressure` : float The pressure applied to the cursor, in range 0.0 (no pressure) to 1.0 (full pressure). `tilt_x` : float Currently undefined. `tilt_y` : float Currently undefined. :event: ''' TabletCanvas.register_event_type('on_enter') TabletCanvas.register_event_type('on_leave') TabletCanvas.register_event_type('on_motion') class TabletCursor(object): '''A distinct cursor used on a tablet. Most tablets support at least a *stylus* and an *erasor* cursor; this object is used to distinguish them when tablet events are generated. :Ivariables: `name` : str Name of the cursor. ''' # TODO well-defined names for stylus and eraser. def __init__(self, name): self.name = name def __repr__(self): return '%s(%s)' % (self.__class__.__name__, self.name)
Python