1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
3 # This file is part of Hooke.
5 # Hooke is free software: you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation, either
8 # version 3 of the License, or (at your option) any later version.
10 # Hooke is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Lesser General Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with Hooke. If not, see
17 # <http://www.gnu.org/licenses/>.
19 """The `playlist` module provides a :class:`Playlist` and its subclass
20 :class:`FilePlaylist` for manipulating lists of
21 :class:`hooke.curve.Curve`\s.
27 import xml.dom.minidom
29 from . import curve as curve
32 class NoteIndexList (list):
33 """A list that keeps track of a "current" item and additional notes.
35 :attr:`index` (i.e. "bookmark") is the index of the currently
36 current curve. Also keep a :class:`dict` of additional information
39 def __init__(self, name=None):
40 super(NoteIndexList, self).__init__()
46 return '<%s %s>' % (self.__class__.__name__, self.name)
48 def _setup_item(self, item):
49 """Perform any required initialization before returning an item.
56 item = self[self._index]
57 self._setup_item(item)
60 def jump(self, index):
64 self._index = index % len(self)
67 self.jump(self._index + 1)
70 self.jump(self._index - 1)
72 def filter(self, keeper_fn=lambda item:True, *args, **kwargs):
73 c = copy.deepcopy(self)
74 for item in reversed(c):
76 if keeper_fn(item, *args, **kwargs) != True:
78 try: # attempt to maintain the same current item
79 c._index = c.index(self.current())
84 class Playlist (NoteIndexList):
85 """A :class:`NoteIndexList` of :class:`hooke.curve.Curve`\s.
87 Keeps a list of :attr:`drivers` for loading curves.
89 def __init__(self, drivers, name=None):
90 super(Playlist, self).__init__(name=name)
91 self.drivers = drivers
92 self._loaded = [] # List of loaded curves, see :meth:`._setup_item`.
93 self._max_loaded = 100 # curves to hold in memory simultaneously.
95 def append_curve_by_path(self, path, info=None, identify=True):
97 path = os.path.join(os.path.dirname(self.path), path)
98 path = os.path.normpath(path)
99 c = curve.Curve(path, info=info)
101 c.identify(self.drivers)
105 def _setup_item(self, curve):
106 if curve != None and curve not in self._loaded:
107 if curve not in self:
109 if curve.driver == None:
110 c.identify(self.drivers)
111 if curve.data == None:
113 self._loaded.append(curve)
114 if len(self._loaded) > self._max_loaded:
115 oldest = self._loaded.pop(0)
118 class FilePlaylist (Playlist):
121 def __init__(self, drivers, name=None, path=None):
122 super(FilePlaylist, self).__init__(drivers, name)
126 def set_path(self, path):
128 if not path.endswith('.hkp'):
131 if self.name == None:
132 self.name = os.path.basename(path)
135 return self.digest() == self._digest
138 r"""Compute the sha1 digest of the flattened playlist
144 >>> root_path = os.path.sep + 'path'
145 >>> p = FilePlaylist(drivers=[],
146 ... path=os.path.join(root_path, 'to','playlist'))
147 >>> p.info['note'] = 'An example playlist'
148 >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'one'))
149 >>> c.info['note'] = 'The first curve'
151 >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'two'))
152 >>> c.info['note'] = 'The second curve'
155 '\\\x14\x87\x88*q\xf8\xaa\xa7\x84f\x82\xa1S>\xfd3+\xd0o'
157 string = self.flatten()
158 return hashlib.sha1(string).digest()
160 def flatten(self, absolute_paths=False):
161 """Create a string representation of the playlist.
163 A playlist is an XML document with the following syntax::
165 <?xml version="1.0" encoding="utf-8"?>
166 <playlist attribute="value">
167 <curve path="/my/file/path/"/ attribute="value" ...>
171 Relative paths are interpreted relative to the location of the
177 >>> root_path = os.path.sep + 'path'
178 >>> p = FilePlaylist(drivers=[],
179 ... path=os.path.join(root_path, 'to','playlist'))
180 >>> p.info['note'] = 'An example playlist'
181 >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'one'))
182 >>> c.info['note'] = 'The first curve'
184 >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'two'))
185 >>> c.info['note'] = 'The second curve'
187 >>> print p.flatten() # doctest: +NORMALIZE_WHITESPACE +REPORT_UDIFF
188 <?xml version="1.0" encoding="utf-8"?>
189 <playlist index="0" note="An example playlist" version="0.1">
190 <curve note="The first curve" path="curve/one"/>
191 <curve note="The second curve" path="curve/two"/>
194 >>> print p.flatten(absolute_paths=True) # doctest: +NORMALIZE_WHITESPACE +REPORT_UDIFF
195 <?xml version="1.0" encoding="utf-8"?>
196 <playlist index="0" note="An example playlist" version="0.1">
197 <curve note="The first curve" path="/path/to/curve/one"/>
198 <curve note="The second curve" path="/path/to/curve/two"/>
202 implementation = xml.dom.minidom.getDOMImplementation()
203 # create the document DOM object and the root element
204 doc = implementation.createDocument(None, 'playlist', None)
205 root = doc.documentElement
206 root.setAttribute('version', self.version) # store playlist version
207 root.setAttribute('index', str(self._index))
208 for key,value in self.info.items(): # save info variables
209 root.setAttribute(key, str(value))
210 for curve in self: # save curves and their attributes
211 curve_element = doc.createElement('curve')
212 root.appendChild(curve_element)
213 path = os.path.abspath(os.path.expanduser(curve.path))
214 if absolute_paths == False:
215 path = os.path.relpath(
219 os.path.expanduser(self.path))))
220 curve_element.setAttribute('path', path)
221 for key,value in curve.info.items():
222 curve_element.setAttribute(key, str(value))
223 string = doc.toprettyxml(encoding='utf-8')
224 root.unlink() # break circular references for garbage collection
227 def _from_xml_doc(self, doc, identify=True):
228 """Load a playlist from an :class:`xml.dom.minidom.Document`
231 root = doc.documentElement
232 for attribute,value in root.attributes.items():
233 if attribute == 'version':
234 assert value == self.version, \
235 'Cannot read v%s playlist with a v%s reader' \
236 % (value, self.version)
237 elif attribute == 'index':
238 self._index = int(value)
240 self.info[attribute] = value
241 for curve_element in doc.getElementsByTagName('curve'):
242 path = curve_element.getAttribute('path')
243 info = dict(curve_element.attributes.items())
245 self.append_curve_by_path(path, info, identify=identify)
246 self.jump(self._index) # ensure valid index
248 def from_string(self, string, identify=True):
249 """Load a playlist from a string.
254 >>> string = '''<?xml version="1.0" encoding="utf-8"?>
255 ... <playlist index="1" note="An example playlist" version="0.1">
256 ... <curve note="The first curve" path="../curve/one"/>
257 ... <curve note="The second curve" path="../curve/two"/>
260 >>> p = FilePlaylist(drivers=[],
261 ... path=os.path.join('path', 'to', 'my', 'playlist'))
262 >>> p.from_string(string, identify=False)
266 {u'note': u'An example playlist'}
272 doc = xml.dom.minidom.parseString(string)
273 self._from_xml_doc(doc, identify=identify)
275 def load(self, path=None, identify=True):
276 """Load a playlist from a file.
279 doc = xml.dom.minidom.parse(self.path)
280 self._from_xml_doc(doc, identify=identify)
281 self._digest = self.digest()
283 def save(self, path=None):
284 """Saves the playlist in a XML file.
287 f = file(self.path, 'w')
288 f.write(self.flatten())