remove some TODO items which have been implemented/rejected
[PyX/mjg.git] / pyx / attr.py
blob69ee6bce8c33afb7d00275e0b18ec2afe50c19d1
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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 and older
31 _isinstance = isinstance
32 def isinstance(instance, clsarg):
33 # we explicitely check for clsarg being a sequence, because
34 # a Leap Before Look pattern, i.e., just trying out
35 # _isinstance(instance, clsarg) within an try/except
36 # block, may mask a TypeError occuring when clsarg is
37 # not a class
38 import helper
39 if not helper.issequence(clsarg):
40 return _isinstance(instance, clsarg)
41 else:
42 for cls in clsarg:
43 if _isinstance(instance, cls):
44 return 1
45 return 0
48 # some helper functions for the attribute handling
51 def mergeattrs(attrs):
52 """perform merging of the attribute list attrs as defined by the
53 merge methods of the attributes"""
54 newattrs = []
55 for a in attrs:
56 # XXX Do we really need this test?
57 if isinstance(a, attr):
58 newattrs = a.merge(newattrs)
59 else:
60 raise TypeError("only instances of class attr.attr are allowed")
61 return newattrs
64 def getattrs(attrs, getclasses):
65 """return all attributes in the attribute list attrs, which are
66 instances of one of the classes in getclasses"""
67 return [attr for attr in attrs if isinstance(attr, tuple(getclasses))]
70 def checkattrs(attrs, allowedclasses):
71 """check whether only attributes which are instances of classes in
72 allowedclasses are present in the attribute list attrs; if not it
73 raises a TypeError"""
74 if len(attrs) != len(getattrs(attrs, allowedclasses)):
75 for attr1, attr2 in zip(attrs, getattrs(attrs, allowedclasses)):
76 if attr1 is not attr2:
77 raise TypeError("instance %r not allowed" % attr1)
78 else:
79 raise TypeError("instance %r not allowed" % attrs[len(getattrs(attrs, allowedclasses))])
82 # attr class and simple descendants
85 class attr:
87 """ attr is the base class of all attributes, i.e., colors, decorators,
88 styles, text attributes and trafos"""
90 def merge(self, attrs):
91 """merge self into list of attrs
93 self may either be appended to attrs or inserted at a proper position
94 immediately before a dependent attribute. Attributes of the same type
95 should be removed, if redundant. Note that it is safe to modify
96 attrs."""
98 attrs.append(self)
99 return attrs
102 class exclusiveattr(attr):
104 """an attribute which swallows all but the last of the same type (specified
105 by the exlusiveclass argument to the constructor) in an attribute list"""
107 def __init__(self, exclusiveclass):
108 self.exclusiveclass = exclusiveclass
110 def merge(self, attrs):
111 attrs = [attr for attr in attrs if not isinstance(attr, self.exclusiveclass)]
112 attrs.append(self)
113 return attrs
116 class sortbeforeattr(attr):
118 """an attribute which places itself previous to all attributes given
119 in the beforetheclasses argument to the constructor"""
121 def __init__(self, beforetheclasses):
122 self.beforetheclasses = tuple(beforetheclasses)
124 def merge(self, attrs):
125 first = 1
126 result = []
127 for attr in attrs:
128 if first and isinstance(attr, self.beforetheclasses):
129 result.append(self)
130 first = 0
131 result.append(attr)
132 if first:
133 result.append(self)
134 return result
137 class sortbeforeexclusiveattr(attr):
139 """an attribute which swallows all but the last of the same type (specified
140 by the exlusiveclass argument to the constructor) in an attribute list and
141 places itself previous to all attributes given in the beforetheclasses
142 argument to the constructor"""
144 def __init__(self, exclusiveclass, beforetheclasses):
145 self.exclusiveclass = exclusiveclass
146 self.beforetheclasses = tuple(beforetheclasses)
148 def merge(self, attrs):
149 first = 1
150 result = []
151 for attr in attrs:
152 if first and isinstance(attr, self.beforetheclasses):
153 result.append(self)
154 first = 0
155 if not isinstance(attr, self.exclusiveclass):
156 result.append(attr)
157 if first:
158 result.append(self)
159 return result
162 class clearclass(attr):
164 """a special attribute which allows to remove all predecessing attributes of
165 the same type in an attribute list"""
167 def __init__(self, clearclass):
168 self.clearclass = clearclass
170 def merge(self, attrs):
171 return [attr for attr in attrs if not isinstance(attr, self.clearclass)]
174 # XXX is _clear a good choice?
176 class _clear(attr):
178 """a special attribute which removes all predecessing attributes
179 in an attribute list"""
181 def merge(self, attrs):
182 return []
184 # we define the attribute "clear", an instance of "_clear",
185 # which can be used to remove all predecessing attributes
186 # in an attribute list
188 clear = _clear()
191 # changeable attrs
194 def selectattrs(attrs, index, total):
195 """performs select calls for all changeable attributes and
196 returns the resulting attribute list
197 - attrs should be a list containing attributes and changeable
198 attributes
199 - index should be an unsigned integer
200 - total should be a positive number
201 - valid sections fullfill 0<=index<total
202 - returns None, when attrs is None
203 - returns None, when a changeable attribute returns None"""
204 if attrs is None:
205 return None
206 result = []
207 for a in attrs:
208 if isinstance(a, changeattr):
209 select = a.select(index, total)
210 if select is None:
211 return None
212 result.append(select)
213 else:
214 result.append(a)
215 return result
218 def selectattr(attr, index, total):
219 """as select, but for a single attribute"""
220 if isinstance(attr, changeattr):
221 select = attr.select(index, total)
222 if select is None:
223 return None
224 return select
225 else:
226 return attr
229 class changeattr:
231 """changeattr is the base class of all changeable attributes"""
233 def select(self, index, total):
234 """returns an attribute for a given index out of a total number
235 if attributes to be provided
236 - index should be an unsigned integer
237 - total should be a positive number
238 - valid selections fullfill 0 <= index < total
239 - the select method may raise a ValueError, when the
240 changeable attribute does not allow for a requested
241 selection"""
243 raise RuntimeError("not implemented")
246 class changelist(changeattr):
248 """a changeable attribute over a list of attribute choises"""
250 def __init__(self, attrs, cyclic=1):
251 """initializes the instance
252 - attrs is a list of attributes to cycle
253 - If cyclic is set, we restart from the beginning after
254 the end of the list has been reached; otherwise
255 selecting beyond the end of the list returns None"""
256 self.attrs = attrs
257 self.cyclic = cyclic
259 def select(self, index, total):
260 if self.cyclic:
261 return self.attrs[index % len(self.attrs)]
262 elif index < len(self.attrs):
263 return self.attrs[index]