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