3 """The `playlist` module provides a :class:`Playlist` and its subclass
4 :class:`FilePlaylist` for manipulating lists of
5 :class:`hooke.curve.Curve`\s.
11 import xml.dom.minidom
13 from . import curve as curve
16 class NoteIndexList (list):
17 """A list that keeps track of a "current" item and additional notes.
19 :attr:`index` (i.e. "bookmark") is the index of the currently
20 current curve. Also keep a :class:`dict` of additional information
23 def __init__(self, name=None):
24 super(NoteIndexList, self).__init__()
32 return self[self._index]
34 def jump(self, index):
38 self._index = index % len(self)
41 self.jump(self._index + 1)
44 self.jump(self._index - 1)
46 def filter(self, keeper_fn=lambda item:True):
47 c = copy.deepcopy(self)
48 for item in reversed(c):
49 if keeper_fn(item) != True:
51 try: # attempt to maintain the same current item
52 c._index = c.index(self.current())
57 class Playlist (NoteIndexList):
58 """A :class:`NoteIndexList` of :class:`hooke.curve.Curve`\s.
60 Keeps a list of :attr:`drivers` for loading curves.
62 def __init__(self, drivers, name=None):
63 super(Playlist, self).__init__(name=name)
64 self.drivers = drivers
66 def append_curve_by_path(self, path, info=None, identify=True):
68 path = os.path.join(self.path, path)
69 path = os.path.normpath(path)
70 c = curve.Curve(path, info=info)
72 c.identify(self.drivers)
76 class FilePlaylist (Playlist):
79 def __init__(self, drivers, name=None, path=None):
80 super(FilePlaylist, self).__init__(drivers, name)
84 def set_path(self, path):
86 if not path.endswith('.hkp'):
90 self.name = os.path.basename(path)
93 return self.digest() == self._digest
96 r"""Compute the sha1 digest of the flattened playlist
102 >>> root_path = os.path.sep + 'path'
103 >>> p = FilePlaylist(drivers=[],
104 ... path=os.path.join(root_path, 'to','playlist'))
105 >>> p.info['note'] = 'An example playlist'
106 >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'one'))
107 >>> c.info['note'] = 'The first curve'
109 >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'two'))
110 >>> c.info['note'] = 'The second curve'
113 "\xa1\x99\x8a\x99\xed\xad\x13'\xa7w\x12\x00\x07Z\xb3\xd0zN\xa2\xe1"
115 string = self.flatten()
116 return hashlib.sha1(string).digest()
118 def flatten(self, absolute_paths=False):
119 """Create a string representation of the playlist.
121 A playlist is an XML document with the following syntax::
123 <?xml version="1.0" encoding="utf-8"?>
124 <playlist attribute="value">
125 <curve path="/my/file/path/"/ attribute="value" ...>
129 Relative paths are interpreted relative to the location of the
135 >>> root_path = os.path.sep + 'path'
136 >>> p = FilePlaylist(drivers=[],
137 ... path=os.path.join(root_path, 'to','playlist'))
138 >>> p.info['note'] = 'An example playlist'
139 >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'one'))
140 >>> c.info['note'] = 'The first curve'
142 >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'two'))
143 >>> c.info['note'] = 'The second curve'
145 >>> print p.flatten() # doctest: +NORMALIZE_WHITESPACE +REPORT_UDIFF
146 <?xml version="1.0" encoding="utf-8"?>
147 <playlist index="0" note="An example playlist" version="0.1">
148 <curve note="The first curve" path="../curve/one"/>
149 <curve note="The second curve" path="../curve/two"/>
152 >>> print p.flatten(absolute_paths=True) # doctest: +NORMALIZE_WHITESPACE +REPORT_UDIFF
153 <?xml version="1.0" encoding="utf-8"?>
154 <playlist index="0" note="An example playlist" version="0.1">
155 <curve note="The first curve" path="/path/to/curve/one"/>
156 <curve note="The second curve" path="/path/to/curve/two"/>
160 implementation = xml.dom.minidom.getDOMImplementation()
161 # create the document DOM object and the root element
162 doc = implementation.createDocument(None, 'playlist', None)
163 root = doc.documentElement
164 root.setAttribute('version', self.version) # store playlist version
165 root.setAttribute('index', str(self._index))
166 for key,value in self.info.items(): # save info variables
167 root.setAttribute(key, str(value))
168 for curve in self: # save curves and their attributes
169 curve_element = doc.createElement('curve')
170 root.appendChild(curve_element)
171 path = os.path.abspath(os.path.expanduser(curve.path))
172 if absolute_paths == False:
173 path = os.path.relpath(
175 os.path.abspath(os.path.expanduser(self.path)))
176 curve_element.setAttribute('path', path)
177 for key,value in curve.info.items():
178 curve_element.setAttribute(key, str(value))
179 string = doc.toprettyxml(encoding='utf-8')
180 root.unlink() # break circular references for garbage collection
183 def _from_xml_doc(self, doc):
184 """Load a playlist from an :class:`xml.dom.minidom.Document`
187 root = doc.documentElement
188 for attribute,value in root.attributes.items():
189 if attribute == 'version':
190 assert value == self.version, \
191 'Cannot read v%s playlist with a v%s reader' \
192 % (value, self.version)
193 elif attribute == 'index':
194 self._index = int(value)
196 self.info[attribute] = value
197 for curve_element in doc.getElementsByTagName('curve'):
198 path = curve_element.getAttribute('path')
199 info = dict(curve_element.attributes.items())
201 self.append_curve_by_path(path, info, identify=False)
202 self.jump(self._index) # ensure valid index
204 def from_string(self, string):
205 """Load a playlist from a string.
210 >>> string = '''<?xml version="1.0" encoding="utf-8"?>
211 ... <playlist index="1" note="An example playlist" version="0.1">
212 ... <curve note="The first curve" path="../curve/one"/>
213 ... <curve note="The second curve" path="../curve/two"/>
216 >>> p = FilePlaylist(drivers=[],
217 ... path=os.path.join('path', 'to','playlist'))
218 >>> p.from_string(string)
222 {u'note': u'An example playlist'}
228 doc = xml.dom.minidom.parseString(string)
229 self._from_xml_doc(doc)
231 def load(self, path=None):
232 """Load a playlist from a file.
235 doc = xml.dom.minidom.parse(self.path)
236 self._from_xml_doc(doc)
237 self._digest = self.digest()
239 def save(self, path=None):
240 """Saves the playlist in a XML file.
243 f = file(self.path, 'w')
244 f.write(self.flatten())