Updated copyright blurbs in all files to '# Copyright'
[hooke.git] / hooke / playlist.py
1 # Copyright
2
3 """The `playlist` module provides a :class:`Playlist` and its subclass
4 :class:`FilePlaylist` for manipulating lists of
5 :class:`hooke.curve.Curve`\s.
6 """
7
8 import copy
9 import hashlib
10 import os.path
11 import xml.dom.minidom
12
13 from . import curve as curve
14
15
16 class NoteIndexList (list):
17     """A list that keeps track of a "current" item and additional notes.
18
19     :attr:`index` (i.e. "bookmark") is the index of the currently
20     current curve.  Also keep a :class:`dict` of additional information
21     (:attr:`info`).
22     """
23     def __init__(self, name=None):
24         super(NoteIndexList, self).__init__()
25         self.name = name
26         self.info = {}
27         self._index = 0
28
29     def current(self):
30         if len(self) == 0:
31             return None
32         return self[self._index]
33
34     def jump(self, index):
35         if len(self) == 0:
36             self._index = 0
37         else:
38             self._index = index % len(self)
39
40     def next(self):
41         self.jump(self._index + 1)
42
43     def previous(self):
44         self.jump(self._index - 1)
45
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:
50                 c.remove(item)
51         try: # attempt to maintain the same current item
52             c._index = c.index(self.current())
53         except ValueError:
54             c._index = 0
55         return c
56
57 class Playlist (NoteIndexList):
58     """A :class:`NoteIndexList` of :class:`hooke.curve.Curve`\s.
59
60     Keeps a list of :attr:`drivers` for loading curves.
61     """
62     def __init__(self, drivers, name=None):
63         super(Playlist, self).__init__(name=name)
64         self.drivers = drivers
65
66     def append_curve_by_path(self, path, info=None, identify=True):
67         if self.path != None:
68             path = os.path.join(self.path, path)
69         path = os.path.normpath(path)
70         c = curve.Curve(path, info=info)
71         if identify == True:
72             c.identify(self.drivers)
73         self.append(c)
74         return c
75
76 class FilePlaylist (Playlist):
77     version = '0.1'
78
79     def __init__(self, drivers, name=None, path=None):
80         super(FilePlaylist, self).__init__(drivers, name)
81         self.set_path(path)
82         self._digest = None
83
84     def set_path(self, path):
85         if path != None:
86             if not path.endswith('.hkp'):
87                 path += '.hkp'
88             self.path = path
89             if self.name == None:
90                 self.name = os.path.basename(path)
91
92     def is_saved(self):
93         return self.digest() == self._digest
94
95     def digest(self):
96         r"""Compute the sha1 digest of the flattened playlist
97         representation.
98
99         Examples
100         --------
101
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'
108         >>> p.append(c)
109         >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'two'))
110         >>> c.info['note'] = 'The second curve'
111         >>> p.append(c)
112         >>> p.digest()
113         "\xa1\x99\x8a\x99\xed\xad\x13'\xa7w\x12\x00\x07Z\xb3\xd0zN\xa2\xe1"
114         """
115         string = self.flatten()
116         return hashlib.sha1(string).digest()
117
118     def flatten(self, absolute_paths=False):
119         """Create a string representation of the playlist.
120
121         A playlist is an XML document with the following syntax::
122
123             <?xml version="1.0" encoding="utf-8"?>
124             <playlist attribute="value">
125               <curve path="/my/file/path/"/ attribute="value" ...>
126               <curve path="...">
127             </playlist>
128
129         Relative paths are interpreted relative to the location of the
130         playlist file.
131         
132         Examples
133         --------
134
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'
141         >>> p.append(c)
142         >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'two'))
143         >>> c.info['note'] = 'The second curve'
144         >>> p.append(c)
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"/>
150         </playlist>
151         <BLANKLINE>
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"/>
157         </playlist>
158         <BLANKLINE>
159         """
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(
174                     path,
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
181         return string
182
183     def _from_xml_doc(self, doc):
184         """Load a playlist from an :class:`xml.dom.minidom.Document`
185         instance.
186         """
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)
195             else:
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())
200             info.pop('path')
201             self.append_curve_by_path(path, info, identify=False)
202         self.jump(self._index) # ensure valid index
203
204     def from_string(self, string):
205         """Load a playlist from a string.
206
207         Examples
208         --------
209
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"/>
214         ... </playlist>
215         ... '''
216         >>> p = FilePlaylist(drivers=[],
217         ...                  path=os.path.join('path', 'to','playlist'))
218         >>> p.from_string(string)
219         >>> p._index
220         1
221         >>> p.info
222         {u'note': u'An example playlist'}
223         >>> for curve in p:
224         ...     print curve.path
225         path/to/curve/one
226         path/to/curve/two
227         """
228         doc = xml.dom.minidom.parseString(string)
229         self._from_xml_doc(doc)
230
231     def load(self, path=None):
232         """Load a playlist from a file.
233         """
234         self.set_path(path)
235         doc = xml.dom.minidom.parse(self.path)
236         self._from_xml_doc(doc)
237         self._digest = self.digest()
238
239     def save(self, path=None):
240         """Saves the playlist in a XML file.
241         """
242         self.set_path(path)
243         f = file(self.path, 'w')
244         f.write(self.flatten())
245         f.close()