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