Correct relative path generation in hooke.playlist.FilePlaylist.flatten
[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, *args, **kwargs):
66         c = copy.deepcopy(self)
67         for item in reversed(c):
68             if keeper_fn(item, *args, **kwargs) != 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         self._loaded = [] # List of loaded curves, see :meth:`._load`.
85         self._max_loaded = 100 # curves to hold in memory simultaneously.
86
87     def append_curve_by_path(self, path, info=None, identify=True):
88         if self.path != None:
89             path = os.path.join(os.path.dirname(self.path), path)
90         path = os.path.normpath(path)
91         c = curve.Curve(path, info=info)
92         if identify == True:
93             c.identify(self.drivers)
94         self.append(c)
95         return c
96
97     def current(self):
98         curve = super(Playlist, self).current()
99         self._load(curve)
100         return curve
101
102     def _load(self, curve):
103         if curve != None and curve not in self._loaded:
104             if curve not in self:
105                 self.append(curve)
106             if curve.driver == None:
107                 c.identify(self.drivers)
108             if curve.data == None:
109                 curve.load()
110             self._loaded.append(curve)
111             if len(self._loaded) > self._max_loaded:
112                 oldest = self._loaded.pop(0)
113                 oldest.unload()
114
115 class FilePlaylist (Playlist):
116     version = '0.1'
117
118     def __init__(self, drivers, name=None, path=None):
119         super(FilePlaylist, self).__init__(drivers, name)
120         self.set_path(path)
121         self._digest = None
122
123     def set_path(self, path):
124         if path != None:
125             if not path.endswith('.hkp'):
126                 path += '.hkp'
127             self.path = path
128             if self.name == None:
129                 self.name = os.path.basename(path)
130
131     def is_saved(self):
132         return self.digest() == self._digest
133
134     def digest(self):
135         r"""Compute the sha1 digest of the flattened playlist
136         representation.
137
138         Examples
139         --------
140
141         >>> root_path = os.path.sep + 'path'
142         >>> p = FilePlaylist(drivers=[],
143         ...                  path=os.path.join(root_path, 'to','playlist'))
144         >>> p.info['note'] = 'An example playlist'
145         >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'one'))
146         >>> c.info['note'] = 'The first curve'
147         >>> p.append(c)
148         >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'two'))
149         >>> c.info['note'] = 'The second curve'
150         >>> p.append(c)
151         >>> p.digest()
152         '\\\x14\x87\x88*q\xf8\xaa\xa7\x84f\x82\xa1S>\xfd3+\xd0o'
153         """
154         string = self.flatten()
155         return hashlib.sha1(string).digest()
156
157     def flatten(self, absolute_paths=False):
158         """Create a string representation of the playlist.
159
160         A playlist is an XML document with the following syntax::
161
162             <?xml version="1.0" encoding="utf-8"?>
163             <playlist attribute="value">
164               <curve path="/my/file/path/"/ attribute="value" ...>
165               <curve path="...">
166             </playlist>
167
168         Relative paths are interpreted relative to the location of the
169         playlist file.
170         
171         Examples
172         --------
173
174         >>> root_path = os.path.sep + 'path'
175         >>> p = FilePlaylist(drivers=[],
176         ...                  path=os.path.join(root_path, 'to','playlist'))
177         >>> p.info['note'] = 'An example playlist'
178         >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'one'))
179         >>> c.info['note'] = 'The first curve'
180         >>> p.append(c)
181         >>> c = curve.Curve(os.path.join(root_path, 'to', 'curve', 'two'))
182         >>> c.info['note'] = 'The second curve'
183         >>> p.append(c)
184         >>> print p.flatten() # doctest: +NORMALIZE_WHITESPACE +REPORT_UDIFF
185         <?xml version="1.0" encoding="utf-8"?>
186         <playlist index="0" note="An example playlist" version="0.1">
187             <curve note="The first curve" path="curve/one"/>
188             <curve note="The second curve" path="curve/two"/>
189         </playlist>
190         <BLANKLINE>
191         >>> print p.flatten(absolute_paths=True) # doctest: +NORMALIZE_WHITESPACE +REPORT_UDIFF
192         <?xml version="1.0" encoding="utf-8"?>
193         <playlist index="0" note="An example playlist" version="0.1">
194             <curve note="The first curve" path="/path/to/curve/one"/>
195             <curve note="The second curve" path="/path/to/curve/two"/>
196         </playlist>
197         <BLANKLINE>
198         """
199         implementation = xml.dom.minidom.getDOMImplementation()
200         # create the document DOM object and the root element
201         doc = implementation.createDocument(None, 'playlist', None)
202         root = doc.documentElement
203         root.setAttribute('version', self.version) # store playlist version
204         root.setAttribute('index', str(self._index))
205         for key,value in self.info.items(): # save info variables
206             root.setAttribute(key, str(value))
207         for curve in self: # save curves and their attributes
208             curve_element = doc.createElement('curve')
209             root.appendChild(curve_element)
210             path = os.path.abspath(os.path.expanduser(curve.path))
211             if absolute_paths == False:
212                 path = os.path.relpath(
213                     path,
214                     os.path.dirname(
215                         os.path.abspath(
216                             os.path.expanduser(self.path))))
217             curve_element.setAttribute('path', path)
218             for key,value in curve.info.items():
219                 curve_element.setAttribute(key, str(value))
220         string = doc.toprettyxml(encoding='utf-8')
221         root.unlink() # break circular references for garbage collection
222         return string
223
224     def _from_xml_doc(self, doc, identify=True):
225         """Load a playlist from an :class:`xml.dom.minidom.Document`
226         instance.
227         """
228         root = doc.documentElement
229         for attribute,value in root.attributes.items():
230             if attribute == 'version':
231                 assert value == self.version, \
232                     'Cannot read v%s playlist with a v%s reader' \
233                     % (value, self.version)
234             elif attribute == 'index':
235                 self._index = int(value)
236             else:
237                 self.info[attribute] = value
238         for curve_element in doc.getElementsByTagName('curve'):
239             path = curve_element.getAttribute('path')
240             info = dict(curve_element.attributes.items())
241             info.pop('path')
242             self.append_curve_by_path(path, info, identify=identify)
243         self.jump(self._index) # ensure valid index
244
245     def from_string(self, string, identify=True):
246         """Load a playlist from a string.
247
248         Examples
249         --------
250
251         >>> string = '''<?xml version="1.0" encoding="utf-8"?>
252         ... <playlist index="1" note="An example playlist" version="0.1">
253         ...     <curve note="The first curve" path="../curve/one"/>
254         ...     <curve note="The second curve" path="../curve/two"/>
255         ... </playlist>
256         ... '''
257         >>> p = FilePlaylist(drivers=[],
258         ...                  path=os.path.join('path', 'to', 'my', 'playlist'))
259         >>> p.from_string(string, identify=False)
260         >>> p._index
261         1
262         >>> p.info
263         {u'note': u'An example playlist'}
264         >>> for curve in p:
265         ...     print curve.path
266         path/to/curve/one
267         path/to/curve/two
268         """
269         doc = xml.dom.minidom.parseString(string)
270         self._from_xml_doc(doc, identify=identify)
271
272     def load(self, path=None, identify=True):
273         """Load a playlist from a file.
274         """
275         self.set_path(path)
276         doc = xml.dom.minidom.parse(self.path)
277         self._from_xml_doc(doc, identify=identify)
278         self._digest = self.digest()
279
280     def save(self, path=None):
281         """Saves the playlist in a XML file.
282         """
283         self.set_path(path)
284         f = file(self.path, 'w')
285         f.write(self.flatten())
286         f.close()