1 """The playlist module provides :class:`Playlist` its subclass
2 :class:`FilePlaylist` for manipulating lists of
3 :class:`hooke.curve.Curve`\s.
11 from . import curve as curve
13 class Playlist (list):
14 """A list of :class:`hooke.curve.Curve`\s.
16 Keeps a list of :attr:`drivers` for loading curves, the
17 :attr:`index` (i.e. "bookmark") of the currently active curve, and
18 a :class:`dict` of additional informtion (:attr:`info`).
20 def __init__(self, drivers, name=None):
21 super(Playlist, self).__init__()
22 self.drivers = drivers
27 def append_curve_by_path(self, path, info=None, identify=True):
29 path = os.path.join(self.path, path)
30 path = os.path.normpath(path)
31 c = curve.Curve(path, info=info)
33 c.identify(self.drivers)
37 def active_curve(self):
38 return self[self._index]
43 def jump(self, index):
47 self._index = index % len(self)
50 self.jump(self._index + 1)
53 self.jump(self._index - 1)
55 def filter(self, keeper_fn=lambda curve:True):
56 playlist = copy.deepcopy(self)
57 for curve in reversed(playlist.curves):
58 if keeper_fn(curve) != True:
59 playlist.curves.remove(curve)
60 try: # attempt to maintain the same active curve
61 playlist._index = playlist.index(self.active_curve())
67 class FilePlaylist (Playlist):
70 def __init__(self, drivers, name=None, path=None):
71 super(FilePlaylist, self).__init__(drivers, name)
75 def set_path(self, path):
76 if not path.endswith('.hkp'):
78 if name == None and path != None:
79 name = os.path.basename(path)
82 return self.digest() == self._digest
85 r"""Compute the sha1 digest of the flattened playlist
91 >>> root_path = os.path.sep + 'path'
92 >>> p = FilePlaylist(drivers=[],
93 ... path=os.path.join(root_path, 'to','playlist'))
94 >>> p.info['note'] = 'An example playlist'
95 >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'one'))
96 >>> c.info['note'] = 'The first curve'
98 >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'two'))
99 >>> c.info['note'] = 'The second curve'
102 "\xa1\x99\x8a\x99\xed\xad\x13'\xa7w\x12\x00\x07Z\xb3\xd0zN\xa2\xe1"
104 string = self.flatten()
105 return hashlib.sha1(string).digest()
107 def flatten(self, absolute_paths=False):
108 """Create a string representation of the playlist.
110 A playlist is an XML document with the following syntax::
112 <?xml version="1.0" encoding="utf-8"?>
113 <playlist attribute="value">
114 <curve path="/my/file/path/"/ attribute="value" ...>
118 Relative paths are interpreted relative to the location of the
124 >>> root_path = os.path.sep + 'path'
125 >>> p = FilePlaylist(drivers=[],
126 ... path=os.path.join(root_path, 'to','playlist'))
127 >>> p.info['note'] = 'An example playlist'
128 >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'one'))
129 >>> c.info['note'] = 'The first curve'
131 >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'two'))
132 >>> c.info['note'] = 'The second curve'
134 >>> print p.flatten() # doctest: +NORMALIZE_WHITESPACE +REPORT_UDIFF
135 <?xml version="1.0" encoding="utf-8"?>
136 <playlist index="0" note="An example playlist" version="0.1">
137 <curve note="The first curve" path="../curve/one"/>
138 <curve note="The second curve" path="../curve/two"/>
141 >>> print p.flatten(absolute_paths=True) # doctest: +NORMALIZE_WHITESPACE +REPORT_UDIFF
142 <?xml version="1.0" encoding="utf-8"?>
143 <playlist index="0" note="An example playlist" version="0.1">
144 <curve note="The first curve" path="/path/to/curve/one"/>
145 <curve note="The second curve" path="/path/to/curve/two"/>
149 implementation = xml.dom.minidom.getDOMImplementation()
150 # create the document DOM object and the root element
151 doc = implementation.createDocument(None, 'playlist', None)
152 root = doc.documentElement
153 root.setAttribute('version', self.version) # store playlist version
154 root.setAttribute('index', str(self._index))
155 for key,value in self.info.items(): # save info variables
156 root.setAttribute(key, str(value))
157 for curve in self: # save curves and their attributes
158 curve_element = doc.createElement('curve')
159 root.appendChild(curve_element)
160 path = os.path.abspath(os.path.expanduser(curve.path))
161 if absolute_paths == False:
162 path = os.path.relpath(
164 os.path.abspath(os.path.expanduser(self.path)))
165 curve_element.setAttribute('path', path)
166 for key,value in curve.info.items():
167 curve_element.setAttribute(key, str(value))
168 string = doc.toprettyxml(encoding='utf-8')
169 root.unlink() # break circular references for garbage collection
172 def _from_xml_doc(self, doc):
173 """Load a playlist from an :class:`xml.dom.minidom.Document`
176 root = doc.documentElement
177 for attribute,value in root.attributes.items():
178 if attribute == 'version':
179 assert value == self.version, \
180 'Cannot read v%s playlist with a v%s reader' \
181 % (value, self.version)
182 elif attribute == 'index':
183 self._index = int(value)
185 self.info[attribute] = value
186 for curve_element in doc.getElementsByTagName('curve'):
187 path = curve_element.getAttribute('path')
188 info = dict(curve_element.attributes.items())
190 self.append_curve_by_path(path, info, identify=False)
191 self.jump(self._index) # ensure valid index
193 def from_string(self, string):
194 """Load a playlist from a string.
199 >>> string = '''<?xml version="1.0" encoding="utf-8"?>
200 ... <playlist index="1" note="An example playlist" version="0.1">
201 ... <curve note="The first curve" path="../curve/one"/>
202 ... <curve note="The second curve" path="../curve/two"/>
205 >>> p = FilePlaylist(drivers=[],
206 ... path=os.path.join('path', 'to','playlist'))
207 >>> p.from_string(string)
211 {u'note': u'An example playlist'}
217 doc = xml.dom.minidom.parseString(string)
218 return self._from_xml_doc(doc)
220 def load(self, path=None):
221 """Load a playlist from a file.
224 doc = xml.dom.minidom.parse(self.path)
225 return self._from_xml_doc(doc)
227 def save(self, path=None):
228 """Saves the playlist in a XML file.
231 f = file(self.path, 'w')
232 f.write(self.flatten())