Commit 405307ba authored by Andrej Shadura's avatar Andrej Shadura

Apply patches.

parent 86e1e70f
......@@ -20,7 +20,7 @@
# as a modular keysym definition and loading mechanism. See the keysym
# definition modules in the Xlib/keysymdef directory.
from X import NoSymbol
from Xlib.X import NoSymbol
def string_to_keysym(keysym):
'''Return the (16 bit) numeric code of keysym.
......
......@@ -17,34 +17,31 @@
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Python modules
import new
import types
# Xlib modules
import error
import ext
import X
from Xlib import error, ext, X
# Xlib.protocol modules
import protocol.display
from protocol import request, event, rq
from Xlib.protocol import display, request, event, rq
# Xlib.xobjects modules
import xobject.resource
import xobject.drawable
import xobject.fontable
import xobject.colormap
import xobject.cursor
import Xlib.xobject.resource
import Xlib.xobject.drawable
import Xlib.xobject.fontable
import Xlib.xobject.colormap
import Xlib.xobject.cursor
_resource_baseclasses = {
'resource': xobject.resource.Resource,
'drawable': xobject.drawable.Drawable,
'window': xobject.drawable.Window,
'pixmap': xobject.drawable.Pixmap,
'fontable': xobject.fontable.Fontable,
'font': xobject.fontable.Font,
'gc': xobject.fontable.GC,
'colormap': xobject.colormap.Colormap,
'cursor': xobject.cursor.Cursor,
'resource': Xlib.xobject.resource.Resource,
'drawable': Xlib.xobject.drawable.Drawable,
'window': Xlib.xobject.drawable.Window,
'pixmap': Xlib.xobject.drawable.Pixmap,
'fontable': Xlib.xobject.fontable.Fontable,
'font': Xlib.xobject.fontable.Font,
'gc': Xlib.xobject.fontable.GC,
'colormap': Xlib.xobject.colormap.Colormap,
'cursor': Xlib.xobject.cursor.Cursor,
}
_resource_hierarchy = {
......@@ -55,18 +52,18 @@ _resource_hierarchy = {
'fontable': ('font', 'gc')
}
class _BaseDisplay(protocol.display.Display):
class _BaseDisplay(display.Display):
resource_classes = _resource_baseclasses.copy()
# Implement a cache of atom names, used by Window objects when
# dealing with some ICCCM properties not defined in Xlib.Xatom
def __init__(self, *args, **keys):
apply(protocol.display.Display.__init__, (self, ) + args, keys)
display.Display.__init__(*(self, ) + args, **keys)
self._atom_cache = {}
def get_atom(self, atomname, only_if_exists=0):
if self._atom_cache.has_key(atomname):
if atomname in self._atom_cache:
return self._atom_cache[atomname]
r = request.InternAtom(display = self, name = atomname, only_if_exists = only_if_exists)
......@@ -119,11 +116,11 @@ class Display:
# Finalize extensions by creating new classes
for type, dict in self.class_extension_dicts.items():
origcls = self.display.resource_classes[type]
self.display.resource_classes[type] = new.classobj(origcls.__name__,
(origcls,),
dict)
for type_, dict in self.class_extension_dicts.items():
origcls = self.display.resource_classes[type_]
self.display.resource_classes[type_] = type(origcls.__name__,
(origcls, object),
dict)
# Problem: we have already created some objects without the
# extensions: the screen roots and default colormaps.
......@@ -211,7 +208,7 @@ class Display:
def __getattr__(self, attr):
try:
function = self.display_extension_methods[attr]
return new.instancemethod(function, self, self.__class__)
return types.MethodType(function, self)
except KeyError:
raise AttributeError(attr)
......@@ -272,13 +269,11 @@ class Display:
if hasattr(cls, name):
raise error.MethodOverrideError('attempting to replace %s method: %s' % (type, name))
method = new.instancemethod(function, None, cls)
# Maybe should check extension overrides too
try:
self.class_extension_dicts[type][name] = method
self.class_extension_dicts[type][name] = function
except KeyError:
self.class_extension_dicts[type] = { name: method }
self.class_extension_dicts[type] = { name: function }
def extension_add_event(self, code, evt, name = None):
"""extension_add_event(code, evt, [name])
......@@ -292,8 +287,8 @@ class Display:
extension_event.
"""
newevt = new.classobj(evt.__name__, evt.__bases__,
evt.__dict__.copy())
newevt = type(evt.__name__, evt.__bases__,
evt.__dict__.copy())
newevt._code = code
self.display.add_extension_event(code, newevt)
......@@ -395,7 +390,7 @@ class Display:
index = 0
for sym in syms:
if sym != X.NoSymbol:
if self._keymap_syms.has_key(sym):
if sym in self._keymap_syms:
symcodes = self._keymap_syms[sym]
symcodes.append((index, code))
symcodes.sort()
......@@ -595,7 +590,7 @@ class Display:
self.display.free_resource_id(fid)
return None
else:
cls = self.display.get_resource_class('font', xobject.fontable.Font)
cls = self.display.get_resource_class('font', Xlib.xobject.fontable.Font)
return cls(self.display, fid, owner = 1)
def list_fonts(self, pattern, max_names):
......
......@@ -16,11 +16,8 @@
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Standard modules
import string
# Xlib modules
import X
from Xlib import X
# Xlib.protocol modules
from Xlib.protocol import rq
......@@ -78,7 +75,7 @@ class XError(rq.GetAttrData, Exception):
'major_opcode', 'minor_opcode'):
s.append('%s = %s' % (f, self._data[f]))
return '%s: %s' % (self.__class__, string.join(s, ', '))
return '%s: %s' % (self.__class__, ', '.join(s))
class XResourceError(XError):
_fields = rq.Struct( rq.Card8('type'), # Always 0
......
......@@ -1139,8 +1139,6 @@ class OutputPropertyNotify(rq.Event):
# Initialization #
def init(disp, info):
print info.__class__
disp.extension_add_method('display', 'xrandr_query_version', query_version)
disp.extension_add_method('window', 'xrandr_select_input', select_input)
disp.extension_add_method('window', 'xrandr_get_screen_info', get_screen_info)
......
......@@ -71,7 +71,7 @@ class RawField(rq.ValueField):
return val, len(val), None
def parse_binary_value(self, data, display, length, format):
return str(data), ''
return data, ''
class GetVersion(rq.ReplyRequest):
......@@ -212,7 +212,7 @@ class EnableContext(rq.ReplyRequest):
def __init__(self, callback, *args, **keys):
self._callback = callback
apply(rq.ReplyRequest.__init__, (self, ) + args, keys)
rq.ReplyRequest.__init__(self, *args, **keys)
def _parse_response(self, data):
r, d = self._reply.parse_binary(data, self._display)
......
......@@ -31,8 +31,17 @@ from Xlib import error
from Xlib.support import lock, connect
# Xlib.protocol modules
import rq
import event
from Xlib.protocol import rq, event
# in Python 3, bytes are an actual array; in python 2, bytes are still
# string-like, so in order to get an array element we need to call ord()
if sys.version[0] >= '3':
def _bytes_item(x):
return x
else:
def _bytes_item(x):
return ord(x)
class Display:
resource_classes = {}
......@@ -83,8 +92,8 @@ class Display:
# Data used by the send-and-recieve loop
self.sent_requests = []
self.request_length = 0
self.data_send = ''
self.data_recv = ''
self.data_send = b''
self.data_recv = b''
self.data_sent_bytes = 0
# Resource ID structures
......@@ -227,7 +236,7 @@ class Display:
self.resource_id_lock.acquire()
try:
i = self.last_resource_id
while self.resource_ids.has_key(i):
while i in self.resource_ids:
i = i + 1
if i > self.info.resource_id_mask:
i = 0
......@@ -503,7 +512,7 @@ class Display:
# Ignore errors caused by a signal recieved while blocking.
# All other errors are re-raised.
except select.error, err:
except select.error as err:
if err[0] != errno.EINTR:
raise err
......@@ -518,7 +527,7 @@ class Display:
if ws:
try:
i = self.socket.send(self.data_send)
except socket.error, err:
except socket.error as err:
self.close_internal('server: %s' % err[1])
raise self.socket_error
......@@ -533,8 +542,8 @@ class Display:
# We're the recieving thread, parse the data
if recieving:
try:
bytes_recv = self.socket.recv(2048)
except socket.error, err:
bytes_recv = self.socket.recv(4096)
except socket.error as err:
self.close_internal('server: %s' % err[1])
raise self.socket_error
......@@ -640,7 +649,7 @@ class Display:
return gotreq
# Check the first byte to find out what kind of response it is
rtype = ord(self.data_recv[0])
rtype = _bytes_item(self.data_recv[0])
# Error resposne
if rtype == 0:
......@@ -660,13 +669,13 @@ class Display:
def parse_error_response(self, request):
# Code is second byte
code = ord(self.data_recv[1])
code = _bytes_item(self.data_recv[1])
# Fetch error class
estruct = self.error_classes.get(code, error.XError)
e = estruct(self, self.data_recv[:32])
self.data_recv = buffer(self.data_recv, 32)
self.data_recv = self.data_recv[32:]
# print 'recv Error:', e
......@@ -720,7 +729,7 @@ class Display:
req._parse_response(self.data_recv[:self.request_length])
# print 'recv Request:', req
self.data_recv = buffer(self.data_recv, self.request_length)
self.data_recv = self.data_recv[self.request_length:]
self.request_length = 0
......@@ -745,7 +754,7 @@ class Display:
e = estruct(display = self, binarydata = self.data_recv[:32])
self.data_recv = buffer(self.data_recv, 32)
self.data_recv = self.data_recv[32:]
# Drop all requests having an error handler,
# but which obviously succeded.
......@@ -967,7 +976,7 @@ class ConnectionSetupRequest(rq.GetAttrData):
def __init__(self, display, *args, **keys):
self._binary = apply(self._request.to_binary, args, keys)
self._binary = self._request.to_binary(*args, **keys)
self._data = None
# Don't bother about locking, since no other threads have
......
......@@ -21,7 +21,7 @@
from Xlib import X
# Xlib.protocol modules
import rq
from Xlib.protocol import rq
class AnyEvent(rq.Event):
......
......@@ -21,8 +21,7 @@
from Xlib import X
# Xlib.protocol modules
import rq
import structs
from Xlib.protocol import rq, structs
class CreateWindow(rq.Request):
......@@ -784,7 +783,7 @@ class ListFontsWithInfo(rq.ReplyRequest):
def __init__(self, *args, **keys):
self._fonts = []
apply(ReplyRequest.__init__, (self, ) + args, keys)
ReplyRequest.__init__(*(self, ) + args, **keys)
def _parse_response(self, data):
......
This diff is collapsed.
......@@ -20,7 +20,7 @@
from Xlib import X
# Xlib.protocol modules
import rq
from Xlib.protocol import rq
def WindowValues(arg):
return rq.ValueList( arg, 4, 0,
......
......@@ -22,13 +22,12 @@
# Standard modules
import string
import types
import re
import sys
import functools
# Xlib modules
from support import lock
from Xlib.support import lock
# Set up a few regexpes for parsing string representation of resources
......@@ -69,7 +68,7 @@ class ResourceDB:
"""
if type(file) is types.StringType:
if type(file) is str:
file = open(file, 'r')
self.insert_string(file.read())
......@@ -84,7 +83,7 @@ class ResourceDB:
"""
# First split string into lines
lines = string.split(data, '\n')
lines = data.split('\n')
while lines:
line = lines[0]
......@@ -122,15 +121,15 @@ class ResourceDB:
for i in range(1, len(splits), 2):
s = splits[i]
if len(s) == 3:
splits[i] = chr(string.atoi(s, 8))
splits[i] = chr(int(s, 8))
elif s == 'n':
splits[i] = '\n'
# strip the last value part to get rid of any
# unescaped blanks
splits[-1] = string.rstrip(splits[-1])
splits[-1] = splits[-1].rstrip()
value = string.join(splits, '')
value = ''.join(splits)
self.insert(res, value)
......@@ -172,7 +171,7 @@ class ResourceDB:
for i in range(1, len(parts), 2):
# Create a new mapping/value group
if not db.has_key(parts[i - 1]):
if parts[i - 1] not in db:
db[parts[i - 1]] = ({}, {})
# Use second mapping if a loose binding, first otherwise
......@@ -182,24 +181,25 @@ class ResourceDB:
db = db[parts[i - 1]][0]
# Insert value into the derived db
if db.has_key(parts[-1]):
if parts[-1] in db:
db[parts[-1]] = db[parts[-1]][:2] + (value, )
else:
db[parts[-1]] = ({}, {}, value)
self.lock.release()
def __getitem__(self, (name, cls)):
def __getitem__(self, nc):
"""db[name, class]
Return the value matching the resource identified by NAME and
CLASS. If no match is found, KeyError is raised.
"""
name, cls = nc
# Split name and class into their parts
namep = string.split(name, '.')
clsp = string.split(cls, '.')
namep = name.split('.')
clsp = cls.split('.')
# It is an error for name and class to have different number
# of parts
......@@ -218,13 +218,13 @@ class ResourceDB:
# Precedence order: name -> class -> ?
if self.db.has_key(namep[0]):
if namep[0] in self.db:
bin_insert(matches, _Match((NAME_MATCH, ), self.db[namep[0]]))
if self.db.has_key(clsp[0]):
if clsp[0] in self.db:
bin_insert(matches, _Match((CLASS_MATCH, ), self.db[clsp[0]]))
if self.db.has_key('?'):
if '?' in self.db:
bin_insert(matches, _Match((WILD_MATCH, ), self.db['?']))
......@@ -240,7 +240,7 @@ class ResourceDB:
# Special case for resources which begins with a loose
# binding, e.g. '*foo.bar'
if self.db.has_key(''):
if '' in self.db:
bin_insert(matches, _Match((), self.db[''][1]))
......@@ -376,11 +376,12 @@ class ResourceDB:
return argv
@functools.total_ordering
class _Match:
def __init__(self, path, dbs):
self.path = path
if type(dbs) is types.TupleType:
if type(dbs) is tuple:
self.skip = 0
self.group = dbs
......@@ -388,22 +389,25 @@ class _Match:
self.skip = 1
self.db = dbs
def __cmp__(self, other):
return cmp(self.path, other.path)
def __eq__(self, other):
return self.path == other.path
def __lt__(self, other):
return self.path < other.path
def match_length(self):
return len(self.path)
def match(self, part, score):
if self.skip:
if self.db.has_key(part):
if part in self.db:
return _Match(self.path + (score, ), self.db[part])
else:
return None
else:
if self.group[0].has_key(part):
if part in self.group[0]:
return _Match(self.path + (score, ), self.group[0][part])
elif self.group[1].has_key(part):
elif part in self.group[1]:
return _Match(self.path + (score + 1, ), self.group[1][part])
else:
return None
......@@ -460,7 +464,7 @@ def bin_insert(list, element):
upper = len(list) - 1
while lower <= upper:
center = (lower + upper) / 2
center = (lower + upper) // 2
if element < list[center]:
upper = center - 1
elif element > list[center]:
......@@ -482,7 +486,7 @@ def update_db(dest, src):
for comp, group in src.items():
# DEST already contains this component, update it
if dest.has_key(comp):
if comp in dest:
# Update tight and loose binding databases
update_db(dest[comp][0], group[0])
......@@ -536,7 +540,7 @@ def output_escape(value):
('\000', '\\000'),
('\n', '\\n')):
value = string.replace(value, char, esc)
value = value.replace(char, esc)
# If first or last character is space or tab, escape them.
if value[0] in ' \t':
......
......@@ -17,7 +17,6 @@
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import sys
import string
# List the modules which contain the corresponding functions
......@@ -43,7 +42,7 @@ _default_auth_mod = 'unix_connect'
# Figure out which OS we're using.
# sys.platform is either "OS-ARCH" or just "OS".
_parts = string.split(sys.platform, '-')
_parts = sys.platform.split('-')
platform = _parts[0]
del _parts
......@@ -61,8 +60,8 @@ def get_display(display):
"""
modname = _display_mods.get(platform, _default_display_mod)
mod = __import__(modname, globals())
return mod.get_display(display)
mod = __import__('Xlib.support', globals(), fromlist=(modname,))
return getattr(mod, modname).get_display(display)
def get_socket(dname, host, dno):
......@@ -75,8 +74,8 @@ def get_socket(dname, host, dno):
"""
modname = _socket_mods.get(platform, _default_socket_mod)
mod = __import__(modname, globals())
return mod.get_socket(dname, host, dno)
mod = __import__('Xlib.support', globals(), fromlist=(modname,))
return getattr(mod, modname).get_socket(dname, host, dno)
def get_auth(sock, dname, host, dno):
......@@ -90,5 +89,5 @@ def get_auth(sock, dname, host, dno):
"""
modname = _auth_mods.get(platform, _default_auth_mod)
mod = __import__(modname, globals())
return mod.get_auth(sock, dname, host, dno)
mod = __import__('Xlib.support', globals(), fromlist=(modname,))
return getattr(mod, modname).get_auth(sock, dname, host, dno)
......@@ -17,7 +17,6 @@
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import re
import string
import os
import platform
import socket
......@@ -60,6 +59,8 @@ def get_display(display):
name = display
host = m.group(1)
if host == 'unix':
host = ''
dno = int(m.group(2))
screen = m.group(4)
if screen:
......@@ -86,7 +87,7 @@ def get_socket(dname, host, dno):
else:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect('/tmp/.X11-unix/X%d' % dno)
except socket.error, val:
except socket.error as val:
raise error.DisplayConnectionError(dname, str(val))
# Make sure that the connection isn't inherited in child processes
......@@ -106,8 +107,8 @@ def new_get_auth(sock, dname, host, dno):
# Convert the prettyprinted IP number into 4-octet string.
# Sometimes these modules are too damn smart...
octets = string.split(sock.getpeername()[0], '.')
addr = string.join(map(lambda x: chr(int(x)), octets), '')
octets = sock.getpeername()[0].split('.')
addr = ''.join(map(lambda x: chr(int(x)), octets))
else:
family = xauth.FamilyLocal
addr = socket.gethostname()
......@@ -143,9 +144,9 @@ def old_get_auth(sock, dname, host, dno):
# DISPLAY SCHEME COOKIE
# We're interested in the two last parts for the
# connection establishment
lines = string.split(data, '\n')
lines = data.split('\n')
if len(lines) >= 1:
parts = string.split(lines[0], None, 2)
parts = lines[0].split(None, 2)
if len(parts) == 3:
auth_name = parts[1]
hexauth = parts[2]
......@@ -153,12 +154,20 @@ def old_get_auth(sock, dname, host, dno):
# Translate hexcode into binary
for i in range(0, len(hexauth), 2):
auth = auth + chr(string.atoi(hexauth[i:i+2], 16))
auth = auth + chr(int(hexauth[i:i+2], 16))
auth_data = auth
except os.error:
pass
if not auth_data and host=='localhost':
# 127.0.0.1 counts as FamilyLocal, not FamilyInternet
# See Xtransutil.c:ConvertAddress.
# There might be more ways to spell 127.0.0.1 but
# 'localhost', yet this code fixes a the case of
# OpenSSH tunneling X.
return get_auth('unix:%d' % dno, 'unix', dno)
return auth_name, auth_data
get_auth = new_get_auth
......@@ -60,7 +60,7 @@ def get_socket(dname, host, dno):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, 6000 + dno))
except socket.error, val:
except socket.error as val:
raise error.DisplayConnectionError(dname, str(val))
return s
......
......@@ -16,7 +16,12 @@
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import thread
try:
# Python 3
import _thread as thread
except ImportError:
# Python 2
import thread
# We change the allocate_lock function in Xlib.support.lock to
# return a basic Python lock, instead of the default dummy lock
......
......@@ -40,7 +40,7 @@ class Xauthority:
try:
raw = open(filename, 'rb').read()
except IOError, err:
except IOError as err:
raise error.XauthError('~/.Xauthority: %s' % err)
self.entries = []
......@@ -81,13 +81,14 @@ class Xauthority:
if len(data) != length:
break
self.entries.append((family, addr, num, name, data))
except struct.error, e:
print "Xlib.xauth: warning, failed to parse part of xauthority file (%s), aborting all further parsing" % filename
self.entries.append((family, addr.decode('UTF-8'),
num.decode('UTF-8'), name.decode('UTF-8'), data))
except struct.error as e:
print ("Xlib.xauth: warning, failed to parse part of xauthority file (%s), aborting all further parsing" % filename)
#pass
if len(self.entries) == 0:
print "Xlib.xauth: warning, no xauthority details available"
print ("Xlib.xauth: warning, no xauthority details available")
# raise an error? this should get partially caught by the XNoAuthError in get_best_auth..
def __len__(self):
......
......@@ -18,8 +18,7 @@
from Xlib import error
from Xlib.protocol import request
import resource
from Xlib.xobject import resource
import re