Add hooke.playlist.NoteIndexList._setup_item
[hooke.git] / hooke / playlist.py
1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
2 #
3 # This file is part of Hooke.
4 #
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.
9 #
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.
14 #
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/>.
18
19 """The `playlist` module provides a :class:`Playlist` and its subclass
20 :class:`FilePlaylist` for manipulating lists of
21 :class:`hooke.curve.Curve`\s.
22 """
23
24 import copy
25 import hashlib
26 import os.path
27 import xml.dom.minidom
28
29 from . import curve as curve
30
31
32 class NoteIndexList (list):
33     """A list that keeps track of a "current" item and additional notes.
34
35     :attr:`index` (i.e. "bookmark") is the index of the currently
36     current curve.  Also keep a :class:`dict` of additional information
37     (:attr:`info`).
38     """
39     def __init__(self, name=None):
40         super(NoteIndexList, self).__init__()
41         self.name = name
42         self.info = {}
43         self._index = 0
44
45     def __str__(self):
46         return '<%s %s>' % (self.__class__.__name__, self.name)
47
48     def _setup_item(self, item):
49         """Perform any required initialization before returning an item.
50         """
51         pass
52
53     def current(self):
54         if len(self) == 0:
55             return None
56         item = self[self._index]
57         self._setup_item(item)
58         return item
59
60     def jump(self, index):
61         if len(self) == 0:
62             self._index = 0
63         else:
64             self._index = index % len(self)
65
66     def next(self):
67         self.jump(self._index + 1)
68
69     def previous(self):
70         self.jump(self._index - 1)
71
72     def filter(self, keeper_fn=lambda item:True, *args, **kwargs):
73         c = copy.deepcopy(self)
74         for item in reversed(c):
75             c._setup_item(item)
76             if keeper_fn(item, *args, **kwargs) != True:
77                 c.remove(item)
78         try: # attempt to maintain the same current item
79             c._index = c.index(self.current())
80         except ValueError:
81             c._index = 0
82         return c
83
84 class Playlist (NoteIndexList):
85     """A :class:`NoteIndexList` of :class:`hooke.curve.Curve`\s.
86
87     Keeps a list of :attr:`drivers` for loading curves.
88     """
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.
94
95     def append_curve_by_path(self, path, info=None, identify=True):
96         if self.path != None:
97             path = os.path.join(os.path.dirname(self.path), path)
98         path = os.path.normpath(path)
99         c = curve.Curve(path, info=info)
100         if identify == True:
101             c.identify(self.drivers)
102         self.append(c)
103         return c
104
105     def _setup_item(self, curve):
106         if curve != None and curve not in self._loaded:
107             if curve not in self:
108                 self.append(curve)
109             if curve.driver == None:
110                 c.identify(self.drivers)
111             if curve.data == None:
112                 curve.load()
113             self._loaded.append(curve)
114             if len(self._loaded) > self._max_loaded:
115                 oldest = self._loaded.pop(0)
116                 oldest.unload()
117
118 class FilePlaylist (Playlist):
119     version = '0.1'
120
121     def __init__(self, drivers, name=None, path=None):
122         super(FilePlaylist, self).__init__(drivers, name)
123         self.set_path(path)
124         self._digest = None
125
126     def set_path(self, path):
127         if path != None:
128             if not path.endswith('.hkp'):
129                 path += '.hkp'
130             self.path = path
131             if self.name == None:
132                 self.name = os.path.basename(path)
133
134     def is_saved(self):
135         return self.digest() == self._digest
136
137     def digest(self):
138         r"""Compute the sha1 digest of the flattened playlist
139         representation.
140
141         Examples
142         --------
143
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'
150         >>> p.append(c)
151         >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'two'))
152         >>> c.info['note'] = 'The second curve'
153         >>> p.append(c)
154         >>> p.digest()
155         '\\\x14\x87\x88*q\xf8\xaa\xa7\x84f\x82\xa1S>\xfd3+\xd0o'
156         """
157         string = self.flatten()
158         return hashlib.sha1(string).digest()
159
160     def flatten(self, absolute_paths=False):
161         """Create a string representation of the playlist.
162
163         A playlist is an XML document with the following syntax::
164
165             <?xml version="1.0" encoding="utf-8"?>
166             <playlist attribute="value">
167               <curve path="/my/file/path/"/ attribute="value" ...>
168               <curve path="...">
169             </playlist>
170
171         Relative paths are interpreted relative to the location of the
172         playlist file.
173         
174         Examples
175         --------
176
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'
183         >>> p.append(c)
184         >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'two'))
185         >>> c.info['note'] = 'The second curve'
186         >>> p.append(c)
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"/>
192         </playlist>
193         <BLANKLINE>
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"/>
199         </playlist>
200         <BLANKLINE>
201         """
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(
216                     path,
217                     os.path.dirname(
218                         os.path.abspath(
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
225         return string
226
227     def _from_xml_doc(self, doc, identify=True):
228         """Load a playlist from an :class:`xml.dom.minidom.Document`
229         instance.
230         """
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)
239             else:
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())
244             info.pop('path')
245             self.append_curve_by_path(path, info, identify=identify)
246         self.jump(self._index) # ensure valid index
247
248     def from_string(self, string, identify=True):
249         """Load a playlist from a string.
250
251         Examples
252         --------
253
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"/>
258         ... </playlist>
259         ... '''
260         >>> p = FilePlaylist(drivers=[],
261         ...                  path=os.path.join('path', 'to', 'my', 'playlist'))
262         >>> p.from_string(string, identify=False)
263         >>> p._index
264         1
265         >>> p.info
266         {u'note': u'An example playlist'}
267         >>> for curve in p:
268         ...     print curve.path
269         path/to/curve/one
270         path/to/curve/two
271         """
272         doc = xml.dom.minidom.parseString(string)
273         self._from_xml_doc(doc, identify=identify)
274
275     def load(self, path=None, identify=True):
276         """Load a playlist from a file.
277         """
278         self.set_path(path)
279         doc = xml.dom.minidom.parse(self.path)
280         self._from_xml_doc(doc, identify=identify)
281         self._digest = self.digest()
282
283     def save(self, path=None):
284         """Saves the playlist in a XML file.
285         """
286         self.set_path(path)
287         f = file(self.path, 'w')
288         f.write(self.flatten())
289         f.close()