Adjust Hooke internals to use unsafe YAML (not just builtin Python types).
[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 modify it
6 # under the terms of the GNU Lesser General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 #
10 # Hooke is distributed in the hope that it will be useful, but WITHOUT
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 # or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General
13 # 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
27 import os.path
28 import types
29
30 import yaml
31 from yaml.representer import RepresenterError
32
33 from .command_stack import CommandStack
34 from .curve import Curve
35 from .util.itertools import reverse_enumerate
36
37
38 class NoteIndexList (list):
39     """A list that keeps track of a "current" item and additional notes.
40
41     :attr:`index` (i.e. "bookmark") is the index of the currently
42     current curve.  Also keep a :class:`dict` of additional information
43     (:attr:`info`).
44     """
45     def __init__(self, name=None):
46         super(NoteIndexList, self).__init__()
47         self._set_default_attrs()
48         self.__setstate__({'name': name})
49
50     def __str__(self):
51         return str(self.__unicode__())
52
53     def __unicode__(self):
54         return u'<%s %s>' % (self.__class__.__name__, self.name)
55
56     def __repr__(self):
57         return self.__str__()
58
59     def _set_default_attrs(self):
60         self._default_attrs = {
61             'info': {},
62             'name': None,
63             '_index': 0,
64             }
65
66     def __getstate__(self):
67         return self.__dict__.copy()
68
69     def __setstate__(self, state):
70         self._set_default_attrs()
71         if state == True:
72             return
73         self.__dict__.update(self._default_attrs)
74         try:
75             self.__dict__.update(state)
76         except TypeError, e:
77             print state, type(state), e
78         if self.info in [None, {}]:
79             self.info = {}
80
81     def _setup_item(self, item):
82         """Perform any required initialization before returning an item.
83         """
84         pass
85
86     def index(self, value=None, *args, **kwargs):
87         """Extend `list.index`, returning the current index if `value`
88         is `None`.
89         """
90         if value == None:
91             return self._index
92         return super(NoteIndexList, self).index(value, *args, **kwargs)
93
94     def current(self):
95         if len(self) == 0:
96             return None
97         item = self[self._index]
98         self._setup_item(item)
99         return item
100
101     def jump(self, index):
102         if len(self) == 0:
103             self._index = 0
104         else:
105             self._index = index % len(self)
106
107     def next(self):
108         self.jump(self._index + 1)
109
110     def previous(self):
111         self.jump(self._index - 1)
112
113     def items(self, reverse=False):
114         """Iterate through `self` calling `_setup_item` on each item
115         before yielding.
116
117         Notes
118         -----
119         Updates :attr:`_index` during the iteration so
120         :func:`~hooke.plugin.curve.current_curve_callback` works as
121         expected in :class:`~hooke.command.Command`\s called from
122         :class:`~hooke.plugin.playlist.ApplyCommand`.  After the
123         iteration completes, :attr:`_index` is restored to its
124         original value.
125         """
126         index = self._index
127         items = self
128         if reverse == True:
129             items = reverse_enumerate(self)
130         else:
131             items = enumerate(self)
132         for i,item in items:
133             self._index = i
134             self._setup_item(item)
135             yield item
136         self._index = index
137
138     def filter(self, keeper_fn=lambda item:True, load_curves=True,
139                *args, **kwargs):
140         c = copy.deepcopy(self)
141         if load_curves == True:
142             items = c.items(reverse=True)
143         else:
144             items = reversed(c)
145         for item in items: 
146             if keeper_fn(item, *args, **kwargs) != True:
147                 c.remove(item)
148         try: # attempt to maintain the same current item
149             c._index = c.index(self.current())
150         except ValueError:
151             c._index = 0
152         return c
153
154
155 class Playlist (NoteIndexList):
156     """A :class:`NoteIndexList` of :class:`hooke.Curve`\s.
157
158     Keeps a list of :attr:`drivers` for loading curves.
159     """
160     def __init__(self, drivers, name=None):
161         super(Playlist, self).__init__(name=name)
162         self.drivers = drivers
163         self._max_loaded = 100 # curves to hold in memory simultaneously.
164
165     def _set_default_attrs(self):
166         super(Playlist, self)._set_default_attrs()
167         self._default_attrs['drivers'] = []
168         # List of loaded curves, see :meth:`._setup_item`.
169         self._default_attrs['_loaded'] = []
170         self._default_attrs['_max_loaded'] = 100
171
172     def __setstate__(self, state):
173         super(Playlist, self).__setstate__(state)
174         if self.drivers in [None, {}]:
175             self.drivers = []
176         if self._loaded in [None, {}]:
177             self._loaded = []
178
179     def append_curve(self, curve):
180         self.append(curve)
181
182     def append_curve_by_path(self, path, info=None, identify=True, hooke=None):
183         path = os.path.normpath(path)
184         c = Curve(path, info=info)
185         c.set_hooke(hooke)
186         if identify == True:
187             c.identify(self.drivers)
188         self.append(c)
189         return c
190
191     def _setup_item(self, curve):
192         if curve != None and curve not in self._loaded:
193             if curve not in self:
194                 self.append(curve)
195             if curve.driver == None:
196                 c.identify(self.drivers)
197             if curve.data == None:
198                 curve.load()
199             self._loaded.append(curve)
200             if len(self._loaded) > self._max_loaded:
201                 oldest = self._loaded.pop(0)
202                 oldest.unload()
203
204
205 class FilePlaylist (Playlist):
206     """A file-backed :class:`Playlist`.
207
208     Examples
209     --------
210
211     >>> p = FilePlaylist(drivers=['Driver A', 'Driver B'])
212     >>> p.append(Curve('dummy/path/A'))
213     >>> p.append(Curve('dummy/path/B'))
214
215     The data-type is pickleable, to ensure we can move it between
216     processes with :class:`multiprocessing.Queue`\s.
217
218     >>> import pickle
219     >>> s = pickle.dumps(p)
220     >>> z = pickle.loads(s)
221     >>> for curve in z:
222     ...     print curve
223     <Curve A>
224     <Curve B>
225     >>> print z.drivers
226     ['Driver A', 'Driver B']
227
228     The data-type is also YAMLable (see :mod:`hooke.util.yaml`).
229
230     >>> s = yaml.dump(p)
231     >>> z = yaml.load(s)
232     >>> for curve in z:
233     ...     print curve
234     <Curve A>
235     <Curve B>
236     >>> print z.drivers
237     ['Driver A', 'Driver B']
238     """
239     version = '0.2'
240
241     def __init__(self, drivers, name=None, path=None):
242         super(FilePlaylist, self).__init__(drivers, name)
243         self.path = self._base_path = None
244         self.set_path(path)
245         self.relative_curve_paths = True
246         self._relative_curve_paths = False
247
248     def _set_default_attrs(self):
249         super(FilePlaylist, self)._set_default_attrs()
250         self._default_attrs['relative_curve_paths'] = True
251         self._default_attrs['_relative_curve_paths'] = False
252         self._default_attrs['_digest'] = None
253
254     def __getstate__(self):
255         state = super(FilePlaylist, self).__getstate__()
256         assert 'version' not in state, state
257         state['version'] = self.version
258         return state
259
260     def __setstate__(self, state):
261         if 'version' in state:
262             version = state.pop('version')
263             assert version == FilePlaylist.version, (
264                 'invalid version %s (%s) != %s (%s)'
265                 % (version, type(version),
266                    FilePlaylist.version, type(FilePlaylist.version)))
267         super(FilePlaylist, self).__setstate__(state)
268
269     def set_path(self, path):
270         orig_base_path = getattr(self, '_base_path', None)
271         if path == None:
272             if self._base_path == None:
273                 self._base_path = os.getcwd()
274         else:
275             if not path.endswith('.hkp'):
276                 path += '.hkp'
277             self.path = path
278             self._base_path = os.path.dirname(os.path.abspath(
279                 os.path.expanduser(self.path)))
280             if self.name == None:
281                 self.name = os.path.basename(path)
282         if self._base_path != orig_base_path:
283             self.update_curve_paths()
284
285     def update_curve_paths(self):
286         for curve in self:
287             curve.set_path(self._curve_path(curve.path))
288
289     def _curve_path(self, path):
290         if self._base_path == None:
291             self._base_path = os.getcwd()
292         path = os.path.join(self._base_path, path)
293         if self._relative_curve_paths == True:
294             path = os.path.relpath(path, self._base_path)
295         return path
296
297     def append_curve(self, curve):
298         curve.set_path(self._curve_path(curve.path))
299         super(FilePlaylist, self).append_curve(curve)
300
301     def append_curve_by_path(self, path, *args, **kwargs):
302         path = self._curve_path(path)
303         super(FilePlaylist, self).append_curve_by_path(path, *args, **kwargs)
304
305     def is_saved(self):
306         return self.digest() == self._digest
307
308     def digest(self):
309         r"""Compute the sha1 digest of the flattened playlist
310         representation.
311
312         Examples
313         --------
314
315         >>> root_path = os.path.sep + 'path'
316         >>> p = FilePlaylist(drivers=[],
317         ...                  path=os.path.join(root_path, 'to','playlist'))
318         >>> p.info['note'] = 'An example playlist'
319         >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'one'))
320         >>> c.info['note'] = 'The first curve'
321         >>> p.append_curve(c)
322         >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'two'))
323         >>> c.info['note'] = 'The second curve'
324         >>> p.append_curve(c)
325         >>> p.digest()
326         'f\xe26i\xb98i\x1f\xb61J7:\xf2\x8e\x1d\xde\xc3}g'
327         """
328         string = self.flatten()
329         return hashlib.sha1(string).digest()
330
331     def flatten(self):
332         """Create a string representation of the playlist.
333
334         A playlist is a YAML document with the following minimal syntax::
335
336             !!python/object/new:hooke.playlist.FilePlaylist
337             state:
338               version: '0.2'
339             listitems:
340             - !!python/object:hooke.curve.Curve
341               path: /path/to/curve/one
342             - !!python/object:hooke.curve.Curve
343               path: /path/to/curve/two
344
345         Relative paths are interpreted relative to the location of the
346         playlist file.
347
348         Examples
349         --------
350
351         >>> from .engine import CommandMessage
352
353         >>> root_path = os.path.sep + 'path'
354         >>> p = FilePlaylist(drivers=[],
355         ...                  path=os.path.join(root_path, 'to','playlist'))
356         >>> p.info['note'] = 'An example playlist'
357         >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'one'))
358         >>> c.info['note'] = 'The first curve'
359         >>> p.append_curve(c)
360         >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'two'))
361         >>> c.info['attr with spaces'] = 'The second curve\\nwith endlines'
362         >>> c.command_stack.extend([
363         ...         CommandMessage('command A', {'arg 0':0, 'arg 1':'X'}),
364         ...         CommandMessage('command B', {'arg 0':1, 'curve':c}),
365         ...         ])
366         >>> p.append_curve(c)
367         >>> print p.flatten()  # doctest: +REPORT_UDIFF
368         # Hooke playlist version 0.2
369         !!python/object/new:hooke.playlist.FilePlaylist
370         listitems:
371         - !!python/object:hooke.curve.Curve
372           info: {note: The first curve}
373           name: one
374           path: curve/one
375         - &id001 !!python/object:hooke.curve.Curve
376           command_stack: !!python/object/new:hooke.command_stack.CommandStack
377             listitems:
378             - !!python/object:hooke.engine.CommandMessage
379               arguments: {arg 0: 0, arg 1: X}
380               command: command A
381             - !!python/object:hooke.engine.CommandMessage
382               arguments:
383                 arg 0: 1
384                 curve: *id001
385               command: command B
386           info: {attr with spaces: 'The second curve
387         <BLANKLINE>
388               with endlines'}
389           name: two
390           path: curve/two
391         state:
392           _base_path: /path/to
393           info: {note: An example playlist}
394           name: playlist.hkp
395           path: /path/to/playlist.hkp
396           version: '0.2'
397         <BLANKLINE>
398         >>> p.relative_curve_paths = False
399         >>> print p.flatten()  # doctest: +REPORT_UDIFF
400         # Hooke playlist version 0.2
401         !!python/object/new:hooke.playlist.FilePlaylist
402         listitems:
403         - !!python/object:hooke.curve.Curve
404           info: {note: The first curve}
405           name: one
406           path: /path/to/curve/one
407         - &id001 !!python/object:hooke.curve.Curve
408           command_stack: !!python/object/new:hooke.command_stack.CommandStack
409             listitems:
410             - !!python/object:hooke.engine.CommandMessage
411               arguments: {arg 0: 0, arg 1: X}
412               command: command A
413             - !!python/object:hooke.engine.CommandMessage
414               arguments:
415                 arg 0: 1
416                 curve: *id001
417               command: command B
418           info: {attr with spaces: 'The second curve
419         <BLANKLINE>
420               with endlines'}
421           name: two
422           path: /path/to/curve/two
423         state:
424           _base_path: /path/to
425           info: {note: An example playlist}
426           name: playlist.hkp
427           path: /path/to/playlist.hkp
428           relative_curve_paths: false
429           version: '0.2'
430         <BLANKLINE>
431         """
432         rcp = self._relative_curve_paths
433         self._relative_curve_paths = self.relative_curve_paths
434         self.update_curve_paths()
435         self._relative_curve_paths = rcp
436
437         yaml_string = yaml.dump(self, allow_unicode=True)
438         self.update_curve_paths()
439         return ('# Hooke playlist version %s\n' % self.version) + yaml_string
440
441     def save(self, path=None, makedirs=True):
442         """Saves the playlist to a YAML file.
443         """
444         self.set_path(path)
445         dirname = os.path.dirname(self.path) or '.'
446         if makedirs == True and not os.path.isdir(dirname):
447             os.makedirs(dirname)
448         with open(self.path, 'w') as f:
449             f.write(self.flatten())
450             self._digest = self.digest()
451
452
453 def from_string(string):
454     u"""Load a playlist from a string.
455
456     Examples
457     --------
458
459     Minimal example.
460
461     >>> string = '''# Hooke playlist version 0.2
462     ... !!python/object/new:hooke.playlist.FilePlaylist
463     ... state:
464     ...   version: '0.2'
465     ... listitems:
466     ... - !!python/object:hooke.curve.Curve
467     ...   path: curve/one
468     ... - !!python/object:hooke.curve.Curve
469     ...   path: curve/two
470     ... '''
471     >>> p = from_string(string)
472     >>> p.set_path('/path/to/playlist')
473     >>> for curve in p:
474     ...     print curve.name, curve.path
475     one /path/to/curve/one
476     two /path/to/curve/two
477
478     More complicated example.
479
480     >>> string = '''# Hooke playlist version 0.2
481     ... !!python/object/new:hooke.playlist.FilePlaylist
482     ... listitems:
483     ... - !!python/object:hooke.curve.Curve
484     ...   info: {note: The first curve}
485     ...   name: one
486     ...   path: /path/to/curve/one
487     ... - &id001 !!python/object:hooke.curve.Curve
488     ...   command_stack: !!python/object/new:hooke.command_stack.CommandStack
489     ...     listitems:
490     ...     - !!python/object:hooke.engine.CommandMessage
491     ...       arguments: {arg 0: 0, arg 1: X}
492     ...       command: command A
493     ...     - !!python/object:hooke.engine.CommandMessage
494     ...       arguments:
495     ...         arg 0: 1
496     ...         curve: *id001
497     ...       command: command B
498     ...   info: {attr with spaces: 'The second curve
499     ... 
500     ...       with endlines'}
501     ...   name: two
502     ...   path: /path/to/curve/two
503     ... state:
504     ...   _base_path: /path/to
505     ...   _index: 1
506     ...   info: {note: An example playlist}
507     ...   name: playlist.hkp
508     ...   path: /path/to/playlist.hkp
509     ...   version: '0.2'
510     ... '''
511     >>> p = from_string(string)
512     >>> p.set_path('/path/to/playlist')
513     >>> p._index
514     1
515     >>> p.info
516     {'note': 'An example playlist'}
517     >>> for curve in p:
518     ...     print curve.name, curve.path
519     one /path/to/curve/one
520     two /path/to/curve/two
521     >>> p[-1].info['attr with spaces']
522     'The second curve\\nwith endlines'
523     >>> type(p[-1].command_stack)
524     <class 'hooke.command_stack.CommandStack'>
525     >>> p[0].command_stack
526     []
527     >>> type(p[0].command_stack)
528     <class 'hooke.command_stack.CommandStack'>
529     >>> p[-1].command_stack  # doctest: +NORMALIZE_WHITESPACE
530     [<CommandMessage command A {arg 0: 0, arg 1: X}>,
531      <CommandMessage command B {arg 0: 1, curve: <Curve two>}>]
532     >>> type(p[1].command_stack)
533     <class 'hooke.command_stack.CommandStack'>
534     >>> c2 = p[-1]
535     >>> c2.command_stack[-1].arguments['curve'] == c2
536     True
537     """
538     return yaml.load(string)
539
540 def load(path=None, identify=True, hooke=None):
541     """Load a playlist from a file.
542     """
543     with open(self.path, 'r') as f:
544         text = f.read()
545     playlist = from_string(text)
546     playlist._digest = playlist.digest()
547     for curve in playlist:
548         curve.set_hooke(hooke)
549         if identify == True:
550             curve.identify(playlist.drivers)
551     return playlist
552
553
554 class Playlists (NoteIndexList):
555     """A :class:`NoteIndexList` of :class:`FilePlaylist`\s.
556     """
557     pass