switch to fix-sized ints
[PyX.git] / pyx / attr.py
blob435200c4d8787de41cdf93ea539fbf2970494c1a
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 try:
35 _isinstance(clsarg, types.ClassType)
36 except:
37 for cls in clsarg:
38 if _isinstance(instance, cls):
39 return 1
40 return 0
41 else:
42 return _isinstance(instance, clsarg)
45 # some helper functions for the attribute handling
48 def mergeattrs(attrs):
49 """perform merging of the attribute list attrs as defined by the
50 merge methods of the attributes"""
51 newattrs = []
52 for a in attrs:
53 # XXX Do we really need this test?
54 if isinstance(a, attr):
55 newattrs = a.merge(newattrs)
56 else:
57 raise TypeError("only instances of class attr.attr are allowed")
58 return newattrs
61 def getattrs(attrs, getclasses):
62 """return all attributes in the attribute list attrs, which are
63 instances of one of the classes in getclasses"""
64 return [attr for attr in attrs if isinstance(attr, tuple(getclasses))]
67 def checkattrs(attrs, allowedclasses):
68 """check whether only attributes which are instances of classes in
69 allowedclasses are present in the attribute list attrs; if not it
70 raises a TypeError"""
71 if len(attrs) != len(getattrs(attrs, allowedclasses)):
72 for attr1, attr2 in zip(attrs, getattrs(attrs, allowedclasses)):
73 if attr1 is not attr2:
74 raise TypeError("instance %r not allowed" % attr1)
75 else:
76 raise TypeError("instance %r not allowed" % attrs[len(getattrs(attrs, allowedclasses))])
79 # attr class and simple descendants
82 class attr:
84 """ attr is the base class of all attributes, i.e., colors, decorators,
85 styles, text attributes and trafos"""
87 def merge(self, attrs):
88 """merge self into list of attrs
90 self may either be appended to attrs or inserted at a proper position
91 immediately before a dependent attribute. Attributes of the same type
92 should be removed, if redundant. Note that it is safe to modify
93 attrs."""
95 attrs.append(self)
96 return attrs
99 class exclusiveattr(attr):
101 """an attribute which swallows all but the last of the same type (specified
102 by the exlusiveclass argument to the constructor) in an attribute list"""
104 def __init__(self, exclusiveclass):
105 self.exclusiveclass = exclusiveclass
107 def merge(self, attrs):
108 attrs = [attr for attr in attrs if not isinstance(attr, self.exclusiveclass)]
109 attrs.append(self)
110 return attrs
113 class sortbeforeattr(attr):
115 """an attribute which places itself previous to all attributes given
116 in the beforetheclasses argument to the constructor"""
118 def __init__(self, beforetheclasses):
119 self.beforetheclasses = tuple(beforetheclasses)
121 def merge(self, attrs):
122 first = 1
123 result = []
124 for attr in attrs:
125 if first and isinstance(attr, self.beforetheclasses):
126 result.append(self)
127 first = 0
128 result.append(attr)
129 if first:
130 result.append(self)
131 return result
134 class sortbeforeexclusiveattr(attr):
136 """an attribute which swallows all but the last of the same type (specified
137 by the exlusiveclass argument to the constructor) in an attribute list and
138 places itself previous to all attributes given in the beforetheclasses
139 argument to the constructor"""
141 def __init__(self, exclusiveclass, beforetheclasses):
142 self.exclusiveclass = exclusiveclass
143 self.beforetheclasses = tuple(beforetheclasses)
145 def merge(self, attrs):
146 first = 1
147 result = []
148 for attr in attrs:
149 if first and isinstance(attr, self.beforetheclasses):
150 result.append(self)
151 first = 0
152 if not isinstance(attr, self.exclusiveclass):
153 result.append(attr)
154 if first:
155 result.append(self)
156 return result
159 class clearclass(attr):
161 """a special attribute which allows to remove all predecessing attributes of
162 the same type in an attribute list"""
164 def __init__(self, clearclass):
165 self.clearclass = clearclass
167 def merge(self, attrs):
168 return [attr for attr in attrs if not isinstance(attr, self.clearclass)]
171 class _clear(attr):
173 """a special attribute which removes all predecessing attributes
174 in an attribute list"""
176 def merge(self, attrs):
177 return []
179 # we define the attribute "clear", an instance of "_clear",
180 # which can be used to remove all predecessing attributes
181 # in an attribute list
183 clear = _clear()
186 # changeable attrs
189 def selectattrs(attrs, index, total):
190 """performs select calls for all changeable attributes and
191 returns the resulting attribute list
192 - attrs should be a list containing attributes and changeable
193 attributes
194 - index should be an unsigned integer
195 - total should be a positive number
196 - valid sections fullfill 0<=index<total
197 - returns None, when attrs is None
198 - returns None, when a changeable attribute returns None"""
199 if attrs is None:
200 return None
201 result = []
202 for a in attrs:
203 if isinstance(a, changeattr):
204 select = a.select(index, total)
205 if select is None:
206 return None
207 result.append(select)
208 else:
209 result.append(a)
210 return result
213 def selectattr(attr, index, total):
214 """as select, but for a single attribute"""
215 if isinstance(attr, changeattr):
216 select = attr.select(index, total)
217 if select is None:
218 return None
219 return select
220 else:
221 return attr
224 class changeattr:
226 """changeattr is the base class of all changeable attributes"""
228 def select(self, index, total):
229 """returns an attribute for a given index out of a total number
230 if attributes to be provided
231 - index should be an unsigned integer
232 - total should be a positive number
233 - valid selections fullfill 0 <= index < total
234 - the select method may raise a ValueError, when the
235 changeable attribute does not allow for a requested
236 selection"""
238 raise RuntimeError("not implemented")
241 class changelist(changeattr):
243 """a changeable attribute over a list of attribute choises"""
245 def __init__(self, attrs, cyclic=1):
246 """initializes the instance
247 - attrs is a list of attributes to cycle
248 - If cyclic is set, we restart from the beginning after
249 the end of the list has been reached; otherwise
250 selecting beyond the end of the list returns None"""
251 self.attrs = attrs
252 self.cyclic = cyclic
254 def select(self, index, total):
255 if self.cyclic:
256 return self.attrs[index % len(self.attrs)]
257 elif index < len(self.attrs):
258 return self.attrs[index]
259 else:
260 return None