Oops, I'd forgotten to version the restored hooke.playlist module.
[hooke.git] / hooke / playlist.py
1 """The playlist module provides :class:`Playlist` its subclass
2 :class:`FilePlaylist` for manipulating lists of
3 :class:`hooke.curve.Curve`\s.
4 """
5
6 import copy
7 import hashlib
8 import os.path
9 import xml.dom.minidom
10
11 from . import curve as curve
12
13 class Playlist (list):
14     """A list of :class:`hooke.curve.Curve`\s.
15
16     Keeps a list of :attr:`drivers` for loading curves, the
17     :attr:`index` (i.e. "bookmark") of the currently active curve, and
18     a :class:`dict` of additional informtion (:attr:`info`).
19     """
20     def __init__(self, drivers, name=None):
21         super(Playlist, self).__init__()
22         self.drivers = drivers
23         self.name = name
24         self.info = {}
25         self._index = 0
26
27     def append_curve_by_path(self, path, info=None, identify=True):
28         if self.path != None:
29             path = os.path.join(self.path, path)
30         path = os.path.normpath(path)
31         c = curve.Curve(path, info=info)
32         if identify == True:
33             c.identify(self.drivers)
34         self.append(c)
35         return c
36
37     def active_curve(self):
38         return self[self._index]
39
40     def has_curves(self):
41         return len(self) > 0
42
43     def jump(self, index):
44         if len(self) == 0:
45             self._index = 0
46         else:
47             self._index = index % len(self)
48
49     def next(self):
50         self.jump(self._index + 1)
51
52     def previous(self):
53         self.jump(self._index - 1)
54
55     def filter(self, keeper_fn=lambda curve:True):
56         playlist = copy.deepcopy(self)
57         for curve in reversed(playlist.curves):
58             if keeper_fn(curve) != True:
59                 playlist.curves.remove(curve)
60         try: # attempt to maintain the same active curve
61             playlist._index = playlist.index(self.active_curve())
62         except ValueError:
63             playlist._index = 0
64         return playlist
65
66 class FilePlaylist (Playlist):
67     version = '0.1'
68
69     def __init__(self, drivers, name=None, path=None):
70         if name == None and path != None:
71             name = os.path.basename(path)
72         super(FilePlaylist, self).__init__(drivers, name)
73         self.path = path
74         self._digest = None
75
76     def is_saved(self):
77         return self.digest() == self._digest
78
79     def digest(self):
80         r"""Compute the sha1 digest of the flattened playlist
81         representation.
82
83         Examples
84         --------
85
86         >>> root_path = os.path.sep + 'path'
87         >>> p = FilePlaylist(drivers=[],
88         ...                  path=os.path.join(root_path, 'to','playlist'))
89         >>> p.info['note'] = 'An example playlist'
90         >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'one'))
91         >>> c.info['note'] = 'The first curve'
92         >>> p.append(c)
93         >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'two'))
94         >>> c.info['note'] = 'The second curve'
95         >>> p.append(c)
96         >>> p.digest()
97         "\xa1\x99\x8a\x99\xed\xad\x13'\xa7w\x12\x00\x07Z\xb3\xd0zN\xa2\xe1"
98         """
99         string = self.flatten()
100         return hashlib.sha1(string).digest()
101
102     def flatten(self, absolute_paths=False):
103         """Create a string representation of the playlist.
104
105         A playlist is an XML document with the following syntax::
106
107             <?xml version="1.0" encoding="utf-8"?>
108             <playlist attribute="value">
109               <curve path="/my/file/path/"/ attribute="value" ...>
110               <curve path="...">
111             </playlist>
112
113         Relative paths are interpreted relative to the location of the
114         playlist file.
115         
116         Examples
117         --------
118
119         >>> root_path = os.path.sep + 'path'
120         >>> p = FilePlaylist(drivers=[],
121         ...                  path=os.path.join(root_path, 'to','playlist'))
122         >>> p.info['note'] = 'An example playlist'
123         >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'one'))
124         >>> c.info['note'] = 'The first curve'
125         >>> p.append(c)
126         >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'two'))
127         >>> c.info['note'] = 'The second curve'
128         >>> p.append(c)
129         >>> print p.flatten() # doctest: +NORMALIZE_WHITESPACE +REPORT_UDIFF
130         <?xml version="1.0" encoding="utf-8"?>
131         <playlist index="0" note="An example playlist" version="0.1">
132             <curve note="The first curve" path="../curve/one"/>
133             <curve note="The second curve" path="../curve/two"/>
134         </playlist>
135         <BLANKLINE>
136         >>> print p.flatten(absolute_paths=True) # doctest: +NORMALIZE_WHITESPACE +REPORT_UDIFF
137         <?xml version="1.0" encoding="utf-8"?>
138         <playlist index="0" note="An example playlist" version="0.1">
139             <curve note="The first curve" path="/path/to/curve/one"/>
140             <curve note="The second curve" path="/path/to/curve/two"/>
141         </playlist>
142         <BLANKLINE>
143         """
144         implementation = xml.dom.minidom.getDOMImplementation()
145         # create the document DOM object and the root element
146         doc = implementation.createDocument(None, 'playlist', None)
147         root = doc.documentElement
148         root.setAttribute('version', self.version) # store playlist version
149         root.setAttribute('index', str(self._index))
150         for key,value in self.info.items(): # save info variables
151             root.setAttribute(key, str(value))
152         for curve in self: # save curves and their attributes
153             curve_element = doc.createElement('curve')
154             root.appendChild(curve_element)
155             path = os.path.abspath(os.path.expanduser(curve.path))
156             if absolute_paths == False:
157                 path = os.path.relpath(
158                     path,
159                     os.path.abspath(os.path.expanduser(self.path)))
160             curve_element.setAttribute('path', path)
161             for key,value in curve.info.items():
162                 curve_element.setAttribute(key, str(value))
163         string = doc.toprettyxml(encoding='utf-8')
164         root.unlink() # break circular references for garbage collection
165         return string
166
167     def _from_xml_doc(self, doc):
168         """Load a playlist from an :class:`xml.dom.minidom.Document`
169         instance.
170         """
171         root = doc.documentElement
172         for attribute,value in root.attributes.items():
173             if attribute == 'version':
174                 assert value == self.version, \
175                     'Cannot read v%s playlist with a v%s reader' \
176                     % (value, self.version)
177             elif attribute == 'index':
178                 self._index = int(value)
179             else:
180                 self.info[attribute] = value
181         for curve_element in doc.getElementsByTagName('curve'):
182             path = curve_element.getAttribute('path')
183             info = dict(curve_element.attributes.items())
184             info.pop('path')
185             self.append_curve_by_path(path, info, identify=False)
186         self.jump(self._index) # ensure valid index
187
188     def from_string(self, string):
189         """Load a playlist from a string.
190
191         Examples
192         --------
193
194         >>> string = '''<?xml version="1.0" encoding="utf-8"?>
195         ... <playlist index="1" note="An example playlist" version="0.1">
196         ...     <curve note="The first curve" path="../curve/one"/>
197         ...     <curve note="The second curve" path="../curve/two"/>
198         ... </playlist>
199         ... '''
200         >>> p = FilePlaylist(drivers=[],
201         ...                  path=os.path.join('path', 'to','playlist'))
202         >>> p.from_string(string)
203         >>> p._index
204         1
205         >>> p.info
206         {u'note': u'An example playlist'}
207         >>> for curve in p:
208         ...     print curve.path
209         path/to/curve/one
210         path/to/curve/two
211         """
212         doc = xml.dom.minidom.parseString(string)
213         return self._from_xml_doc(doc)
214
215     def load(self, path=None):
216         """Load a playlist from a file.
217         """
218         if path != None:
219             self.path = path
220         if self.name == None:
221             self.name = os.path.basename(self.path)
222         doc = xml.dom.minidom.parse(path)
223         return self._from_xml_doc(doc)
224
225     def save(self, path):
226         """Saves the playlist in a XML file.
227         """
228         f = file(path, 'w')
229         f.write(self.flatten())
230         f.close()