fixes to properly support Python versions 2.1 to 2.4
[PyX/mjg.git] / pyx / attr.py
blob35b7ca87614b750b96b0202068cd42f8c11118e4
1 #!/usr/bin/env python
2 # -*- coding: ISO-8859-1 -*-
5 # Copyright (C) 2003-2004 Jörg Lehmann <joergl@users.sourceforge.net>
6 # Copyright (C) 2003-2004 Michael Schindler <m-schindler@users.sourceforge.net>
7 # Copyright (C) 2003-2004 André Wobst <wobsta@users.sourceforge.net>
9 # This file is part of PyX (http://pyx.sourceforge.net/).
11 # PyX is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 2 of the License, or
14 # (at your option) any later version.
16 # PyX is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
21 # You should have received a copy of the GNU General Public License
22 # along with PyX; if not, write to the Free Software
23 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
25 # check for an isinstance which accepts both a class and a sequence of classes
26 # as second argument and emulate this behaviour if necessary
27 try:
28 isinstance(1, (int, float))
29 except TypeError:
30 # workaround for Python 2.1
31 _isinstance = isinstance
32 def isinstance(instance, clsarg):
33 import types
34 if _isinstance(clsarg, types.ClassType):
35 return _isinstance(instance, clsarg)
36 for cls in clsarg:
37 if _isinstance(instance, cls):
38 return 1
39 return 0
42 # some helper functions for the attribute handling
45 def mergeattrs(attrs):
46 """perform merging of the attribute list attrs as defined by the
47 merge methods of the attributes"""
48 newattrs = []
49 for a in attrs:
50 # XXX Do we really need this test?
51 if isinstance(a, attr):
52 newattrs = a.merge(newattrs)
53 else:
54 raise TypeError("only instances of class attr.attr are allowed")
55 return newattrs
58 def getattrs(attrs, getclasses):
59 """return all attributes in the attribute list attrs, which are
60 instances of one of the classes in getclasses"""
61 return [attr for attr in attrs if isinstance(attr, tuple(getclasses))]
64 def checkattrs(attrs, allowedclasses):
65 """check whether only attributes which are instances of classes in
66 allowedclasses are present in the attribute list attrs; if not it
67 raises a TypeError"""
68 if len(attrs) != len(getattrs(attrs, allowedclasses)):
69 for attr1, attr2 in zip(attrs, getattrs(attrs, allowedclasses)):
70 if attr1 is not attr2:
71 raise TypeError("instance %r not allowed" % attr1)
72 else:
73 raise TypeError("instance %r not allowed" % attrs[len(getattrs(attrs, allowedclasses))])
76 # attr class and simple descendants
79 class attr:
81 """ attr is the base class of all attributes, i.e., colors, decorators,
82 styles, text attributes and trafos"""
84 def merge(self, attrs):
85 """merge self into list of attrs
87 self may either be appended to attrs or inserted at a proper position
88 immediately before a dependent attribute. Attributes of the same type
89 should be removed, if redundant. Note that it is safe to modify
90 attrs."""
92 attrs.append(self)
93 return attrs
96 class exclusiveattr(attr):
98 """an attribute which swallows all but the last of the same type (specified
99 by the exlusiveclass argument to the constructor) in an attribute list"""
101 def __init__(self, exclusiveclass):
102 self.exclusiveclass = exclusiveclass
104 def merge(self, attrs):
105 attrs = [attr for attr in attrs if not isinstance(attr, self.exclusiveclass)]
106 attrs.append(self)
107 return attrs
110 class sortbeforeattr(attr):
112 """an attribute which places itself previous to all attributes given
113 in the beforetheclasses argument to the constructor"""
115 def __init__(self, beforetheclasses):
116 self.beforetheclasses = tuple(beforetheclasses)
118 def merge(self, attrs):
119 first = 1
120 result = []
121 for attr in attrs:
122 if first and isinstance(attr, self.beforetheclasses):
123 result.append(self)
124 first = 0
125 result.append(attr)
126 if first:
127 result.append(self)
128 return result
131 class sortbeforeexclusiveattr(attr):
133 """an attribute which swallows all but the last of the same type (specified
134 by the exlusiveclass argument to the constructor) in an attribute list and
135 places itself previous to all attributes given in the beforetheclasses
136 argument to the constructor"""
138 def __init__(self, exclusiveclass, beforetheclasses):
139 self.exclusiveclass = exclusiveclass
140 self.beforetheclasses = tuple(beforetheclasses)
142 def merge(self, attrs):
143 first = 1
144 result = []
145 for attr in attrs:
146 if first and isinstance(attr, self.beforetheclasses):
147 result.append(self)
148 first = 0
149 if not isinstance(attr, self.exclusiveclass):
150 result.append(attr)
151 if first:
152 result.append(self)
153 return result
156 class clearclass(attr):
158 """a special attribute which allows to remove all predecessing attributes of
159 the same type in an attribute list"""
161 def __init__(self, clearclass):
162 self.clearclass = clearclass
164 def merge(self, attrs):
165 return [attr for attr in attrs if not isinstance(attr, self.clearclass)]
168 class _clear(attr):
170 """a special attribute which removes all predecessing attributes
171 in an attribute list"""
173 def merge(self, attrs):
174 return []
176 # we define the attribute "clear", an instance of "_clear",
177 # which can be used to remove all predecessing attributes
178 # in an attribute list
180 clear = _clear()
183 # changeable attrs
186 def selectattrs(attrs, index, total):
187 """performs select calls for all changeable attributes and
188 returns the resulting attribute list
189 - attrs should be a list containing attributes and changeable
190 attributes
191 - index should be an unsigned integer
192 - total should be a positive number
193 - valid sections fullfill 0<=index<total
194 - returns None, when attrs is None
195 - returns None, when a changeable attribute returns None"""
196 if attrs is None:
197 return None
198 result = []
199 for a in attrs:
200 if isinstance(a, changeattr):
201 select = a.select(index, total)
202 if select is None:
203 return None
204 result.append(select)
205 else:
206 result.append(a)
207 return result
210 def selectattr(attr, index, total):
211 """as select, but for a single attribute"""
212 if isinstance(attr, changeattr):
213 select = attr.select(index, total)
214 if select is None:
215 return None
216 return select
217 else:
218 return attr
221 class changeattr:
223 """changeattr is the base class of all changeable attributes"""
225 def select(self, index, total):
226 """returns an attribute for a given index out of a total number
227 if attributes to be provided
228 - index should be an unsigned integer
229 - total should be a positive number
230 - valid selections fullfill 0 <= index < total
231 - the select method may raise a ValueError, when the
232 changeable attribute does not allow for a requested
233 selection"""
235 raise RuntimeError("not implemented")
238 class changelist(changeattr):
240 """a changeable attribute over a list of attribute choises"""
242 def __init__(self, attrs, cyclic=1):
243 """initializes the instance
244 - attrs is a list of attributes to cycle
245 - If cyclic is set, we restart from the beginning after
246 the end of the list has been reached; otherwise
247 selecting beyond the end of the list returns None"""
248 self.attrs = attrs
249 self.cyclic = cyclic
251 def select(self, index, total):
252 if self.cyclic:
253 return self.attrs[index % len(self.attrs)]
254 elif index < len(self.attrs):
255 return self.attrs[index]
256 else:
257 return None