Add hooke.playlist.NoteIndexList.__str__() method.
[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 current(self):
49         if len(self) == 0:
50             return None
51         return self[self._index]
52
53     def jump(self, index):
54         if len(self) == 0:
55             self._index = 0
56         else:
57             self._index = index % len(self)
58
59     def next(self):
60         self.jump(self._index + 1)
61
62     def previous(self):
63         self.jump(self._index - 1)
64
65     def filter(self, keeper_fn=lambda item:True):
66         c = copy.deepcopy(self)
67         for item in reversed(c):
68             if keeper_fn(item) != True:
69                 c.remove(item)
70         try: # attempt to maintain the same current item
71             c._index = c.index(self.current())
72         except ValueError:
73             c._index = 0
74         return c
75
76 class Playlist (NoteIndexList):
77     """A :class:`NoteIndexList` of :class:`hooke.curve.Curve`\s.
78
79     Keeps a list of :attr:`drivers` for loading curves.
80     """
81     def __init__(self, drivers, name=None):
82         super(Playlist, self).__init__(name=name)
83         self.drivers = drivers
84
85     def append_curve_by_path(self, path, info=None, identify=True):
86         if self.path != None:
87             path = os.path.join(self.path, path)
88         path = os.path.normpath(path)
89         c = curve.Curve(path, info=info)
90         if identify == True:
91             c.identify(self.drivers)
92         self.append(c)
93         return c
94
95 class FilePlaylist (Playlist):
96     version = '0.1'
97
98     def __init__(self, drivers, name=None, path=None):
99         super(FilePlaylist, self).__init__(drivers, name)
100         self.set_path(path)
101         self._digest = None
102
103     def set_path(self, path):
104         if path != None:
105             if not path.endswith('.hkp'):
106                 path += '.hkp'
107             self.path = path
108             if self.name == None:
109                 self.name = os.path.basename(path)
110
111     def is_saved(self):
112         return self.digest() == self._digest
113
114     def digest(self):
115         r"""Compute the sha1 digest of the flattened playlist
116         representation.
117
118         Examples
119         --------
120
121         >>> root_path = os.path.sep + 'path'
122         >>> p = FilePlaylist(drivers=[],
123         ...                  path=os.path.join(root_path, 'to','playlist'))
124         >>> p.info['note'] = 'An example playlist'
125         >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'one'))
126         >>> c.info['note'] = 'The first curve'
127         >>> p.append(c)
128         >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'two'))
129         >>> c.info['note'] = 'The second curve'
130         >>> p.append(c)
131         >>> p.digest()
132         "\xa1\x99\x8a\x99\xed\xad\x13'\xa7w\x12\x00\x07Z\xb3\xd0zN\xa2\xe1"
133         """
134         string = self.flatten()
135         return hashlib.sha1(string).digest()
136
137     def flatten(self, absolute_paths=False):
138         """Create a string representation of the playlist.
139
140         A playlist is an XML document with the following syntax::
141
142             <?xml version="1.0" encoding="utf-8"?>
143             <playlist attribute="value">
144               <curve path="/my/file/path/"/ attribute="value" ...>
145               <curve path="...">
146             </playlist>
147
148         Relative paths are interpreted relative to the location of the
149         playlist file.
150         
151         Examples
152         --------
153
154         >>> root_path = os.path.sep + 'path'
155         >>> p = FilePlaylist(drivers=[],
156         ...                  path=os.path.join(root_path, 'to','playlist'))
157         >>> p.info['note'] = 'An example playlist'
158         >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'one'))
159         >>> c.info['note'] = 'The first curve'
160         >>> p.append(c)
161         >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'two'))
162         >>> c.info['note'] = 'The second curve'
163         >>> p.append(c)
164         >>> print p.flatten() # doctest: +NORMALIZE_WHITESPACE +REPORT_UDIFF
165         <?xml version="1.0" encoding="utf-8"?>
166         <playlist index="0" note="An example playlist" version="0.1">
167             <curve note="The first curve" path="../curve/one"/>
168             <curve note="The second curve" path="../curve/two"/>
169         </playlist>
170         <BLANKLINE>
171         >>> print p.flatten(absolute_paths=True) # doctest: +NORMALIZE_WHITESPACE +REPORT_UDIFF
172         <?xml version="1.0" encoding="utf-8"?>
173         <playlist index="0" note="An example playlist" version="0.1">
174             <curve note="The first curve" path="/path/to/curve/one"/>
175             <curve note="The second curve" path="/path/to/curve/two"/>
176         </playlist>
177         <BLANKLINE>
178         """
179         implementation = xml.dom.minidom.getDOMImplementation()
180         # create the document DOM object and the root element
181         doc = implementation.createDocument(None, 'playlist', None)
182         root = doc.documentElement
183         root.setAttribute('version', self.version) # store playlist version
184         root.setAttribute('index', str(self._index))
185         for key,value in self.info.items(): # save info variables
186             root.setAttribute(key, str(value))
187         for curve in self: # save curves and their attributes
188             curve_element = doc.createElement('curve')
189             root.appendChild(curve_element)
190             path = os.path.abspath(os.path.expanduser(curve.path))
191             if absolute_paths == False:
192                 path = os.path.relpath(
193                     path,
194                     os.path.abspath(os.path.expanduser(self.path)))
195             curve_element.setAttribute('path', path)
196             for key,value in curve.info.items():
197                 curve_element.setAttribute(key, str(value))
198         string = doc.toprettyxml(encoding='utf-8')
199         root.unlink() # break circular references for garbage collection
200         return string
201
202     def _from_xml_doc(self, doc):
203         """Load a playlist from an :class:`xml.dom.minidom.Document`
204         instance.
205         """
206         root = doc.documentElement
207         for attribute,value in root.attributes.items():
208             if attribute == 'version':
209                 assert value == self.version, \
210                     'Cannot read v%s playlist with a v%s reader' \
211                     % (value, self.version)
212             elif attribute == 'index':
213                 self._index = int(value)
214             else:
215                 self.info[attribute] = value
216         for curve_element in doc.getElementsByTagName('curve'):
217             path = curve_element.getAttribute('path')
218             info = dict(curve_element.attributes.items())
219             info.pop('path')
220             self.append_curve_by_path(path, info, identify=False)
221         self.jump(self._index) # ensure valid index
222
223     def from_string(self, string):
224         """Load a playlist from a string.
225
226         Examples
227         --------
228
229         >>> string = '''<?xml version="1.0" encoding="utf-8"?>
230         ... <playlist index="1" note="An example playlist" version="0.1">
231         ...     <curve note="The first curve" path="../curve/one"/>
232         ...     <curve note="The second curve" path="../curve/two"/>
233         ... </playlist>
234         ... '''
235         >>> p = FilePlaylist(drivers=[],
236         ...                  path=os.path.join('path', 'to','playlist'))
237         >>> p.from_string(string)
238         >>> p._index
239         1
240         >>> p.info
241         {u'note': u'An example playlist'}
242         >>> for curve in p:
243         ...     print curve.path
244         path/to/curve/one
245         path/to/curve/two
246         """
247         doc = xml.dom.minidom.parseString(string)
248         self._from_xml_doc(doc)
249
250     def load(self, path=None):
251         """Load a playlist from a file.
252         """
253         self.set_path(path)
254         doc = xml.dom.minidom.parse(self.path)
255         self._from_xml_doc(doc)
256         self._digest = self.digest()
257
258     def save(self, path=None):
259         """Saves the playlist in a XML file.
260         """
261         self.set_path(path)
262         f = file(self.path, 'w')
263         f.write(self.flatten())
264         f.close()