Ran update_copyright.py.
[hooke.git] / hooke / playlist.py
1 # Copyright (C) 2010-2011 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, load=True):
95         if len(self) == 0:
96             return None
97         item = self[self._index]
98         if load == True:
99             self._setup_item(item)
100         return item
101
102     def jump(self, index):
103         if len(self) == 0:
104             self._index = 0
105         else:
106             self._index = index % len(self)
107
108     def next(self):
109         self.jump(self._index + 1)
110
111     def previous(self):
112         self.jump(self._index - 1)
113
114     def items(self, reverse=False):
115         """Iterate through `self` calling `_setup_item` on each item
116         before yielding.
117
118         Notes
119         -----
120         Updates :attr:`_index` during the iteration so
121         :func:`~hooke.plugin.curve.current_curve_callback` works as
122         expected in :class:`~hooke.command.Command`\s called from
123         :class:`~hooke.plugin.playlist.ApplyCommand`.  After the
124         iteration completes, :attr:`_index` is restored to its
125         original value.
126         """
127         index = self._index
128         items = self
129         if reverse == True:
130             # could iterate through `c` if current_curve_callback()
131             # would work, but `c` is not bound to the local `hooke`,
132             # so curent_playlist_callback cannot point to it.
133             items = reverse_enumerate(self)
134         else:
135             items = enumerate(self)
136         for i,item in items:
137             self._index = i
138             self._setup_item(item)
139             yield item
140         self._index = index
141
142     def filter(self, keeper_fn=lambda item:True, load_curves=True,
143                *args, **kwargs):
144         c = copy.copy(self)
145         if load_curves == True:
146             items = self.items(reverse=True)
147         else:
148             items = reversed(self)
149         for item in items: 
150             if keeper_fn(item, *args, **kwargs) != True:
151                 c.remove(item)
152         try: # attempt to maintain the same current item
153             c._index = c.index(self.current())
154         except ValueError:
155             c._index = 0
156         return c
157
158
159 class Playlist (NoteIndexList):
160     """A :class:`NoteIndexList` of :class:`hooke.Curve`\s.
161
162     Keeps a list of :attr:`drivers` for loading curves.
163     """
164     def __init__(self, drivers, name=None):
165         super(Playlist, self).__init__(name=name)
166         self.drivers = drivers
167
168     def _set_default_attrs(self):
169         super(Playlist, self)._set_default_attrs()
170         self._default_attrs['drivers'] = []
171         # List of loaded curves, see :meth:`._setup_item`.
172         self._default_attrs['_loaded'] = []
173         self._default_attrs['_max_loaded'] = 100  # curves to hold in memory simultaneously.
174
175     def __setstate__(self, state):
176         super(Playlist, self).__setstate__(state)
177         if self.drivers in [None, {}]:
178             self.drivers = []
179         if self._loaded in [None, {}]:
180             self._loaded = []
181
182     def append_curve(self, curve):
183         self.append(curve)
184
185     def append_curve_by_path(self, path, info=None, identify=True, hooke=None):
186         path = os.path.normpath(path)
187         c = Curve(path, info=info)
188         c.set_hooke(hooke)
189         if identify == True:
190             c.identify(self.drivers)
191         self.append(c)
192         return c
193
194     def _setup_item(self, curve):
195         if curve != None and curve not in self._loaded:
196             if curve not in self:
197                 self.append(curve)
198             if curve.driver == None:
199                 c.identify(self.drivers)
200             if curve.data == None or max([d.size for d in curve.data]) == 0:
201                 curve.load()
202             self._loaded.append(curve)
203             if len(self._loaded) > self._max_loaded:
204                 oldest = self._loaded.pop(0)
205                 oldest.unload()
206
207     def unload(self, curve):
208         "Inverse of `._setup_item`."
209         curve.unload()
210         try:
211             self._loaded.remove(curve)
212         except ValueError:
213             pass
214
215
216 def playlist_path(path):
217     """Normalize playlist path extensions.
218
219     Examples
220     --------
221     >>> print playlist_path('playlist')
222     playlist.hkp
223     >>> print playlist_path('playlist.hkp')
224     playlist.hkp
225     >>> print playlist_path(None)
226     None
227     """
228     if path == None:
229         return None
230     if not path.endswith('.hkp'):
231         path += '.hkp'
232     return path
233
234
235 class FilePlaylist (Playlist):
236     """A file-backed :class:`Playlist`.
237
238     Examples
239     --------
240
241     >>> p = FilePlaylist(drivers=['Driver A', 'Driver B'])
242     >>> p.append(Curve('dummy/path/A'))
243     >>> p.append(Curve('dummy/path/B'))
244
245     The data-type is pickleable, to ensure we can move it between
246     processes with :class:`multiprocessing.Queue`\s.
247
248     >>> import pickle
249     >>> s = pickle.dumps(p)
250     >>> z = pickle.loads(s)
251     >>> for curve in z:
252     ...     print curve
253     <Curve A>
254     <Curve B>
255     >>> print z.drivers
256     ['Driver A', 'Driver B']
257
258     The data-type is also YAMLable (see :mod:`hooke.util.yaml`).
259
260     >>> s = yaml.dump(p)
261     >>> z = yaml.load(s)
262     >>> for curve in z:
263     ...     print curve
264     <Curve A>
265     <Curve B>
266     >>> print z.drivers
267     ['Driver A', 'Driver B']
268     """
269     version = '0.2'
270
271     def __init__(self, drivers, name=None, path=None):
272         super(FilePlaylist, self).__init__(drivers, name)
273         self.path = self._base_path = None
274         self.set_path(path)
275         self.relative_curve_paths = True
276         self._relative_curve_paths = False
277
278     def _set_default_attrs(self):
279         super(FilePlaylist, self)._set_default_attrs()
280         self._default_attrs['relative_curve_paths'] = True
281         self._default_attrs['_relative_curve_paths'] = False
282         self._default_attrs['_digest'] = None
283
284     def __getstate__(self):
285         state = super(FilePlaylist, self).__getstate__()
286         assert 'version' not in state, state
287         state['version'] = self.version
288         return state
289
290     def __setstate__(self, state):
291         if 'version' in state:
292             version = state.pop('version')
293             assert version == FilePlaylist.version, (
294                 'invalid version %s (%s) != %s (%s)'
295                 % (version, type(version),
296                    FilePlaylist.version, type(FilePlaylist.version)))
297         super(FilePlaylist, self).__setstate__(state)
298
299     def set_path(self, path):
300         orig_base_path = getattr(self, '_base_path', None)
301         if path == None:
302             if self._base_path == None:
303                 self._base_path = os.getcwd()
304         else:
305             path = playlist_path(path)
306             self.path = path
307             self._base_path = os.path.dirname(os.path.abspath(
308                 os.path.expanduser(self.path)))
309             if self.name == None:
310                 self.name = os.path.basename(path)
311         if self._base_path != orig_base_path:
312             self.update_curve_paths()
313
314     def update_curve_paths(self):
315         for curve in self:
316             curve.set_path(self._curve_path(curve.path))
317
318     def _curve_path(self, path):
319         if self._base_path == None:
320             self._base_path = os.getcwd()
321         path = os.path.join(self._base_path, path)
322         if self._relative_curve_paths == True:
323             path = os.path.relpath(path, self._base_path)
324         return path
325
326     def append_curve(self, curve):
327         curve.set_path(self._curve_path(curve.path))
328         super(FilePlaylist, self).append_curve(curve)
329
330     def append_curve_by_path(self, path, *args, **kwargs):
331         path = self._curve_path(path)
332         super(FilePlaylist, self).append_curve_by_path(path, *args, **kwargs)
333
334     def is_saved(self):
335         return self.digest() == self._digest
336
337     def digest(self):
338         r"""Compute the sha1 digest of the flattened playlist
339         representation.
340
341         Examples
342         --------
343
344         >>> root_path = os.path.sep + 'path'
345         >>> p = FilePlaylist(drivers=[],
346         ...                  path=os.path.join(root_path, 'to','playlist'))
347         >>> p.info['note'] = 'An example playlist'
348         >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'one'))
349         >>> c.info['note'] = 'The first curve'
350         >>> p.append_curve(c)
351         >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'two'))
352         >>> c.info['note'] = 'The second curve'
353         >>> p.append_curve(c)
354         >>> p.digest()
355         'f\xe26i\xb98i\x1f\xb61J7:\xf2\x8e\x1d\xde\xc3}g'
356         """
357         string = self.flatten()
358         return hashlib.sha1(string).digest()
359
360     def flatten(self):
361         """Create a string representation of the playlist.
362
363         A playlist is a YAML document with the following minimal syntax::
364
365             !!python/object/new:hooke.playlist.FilePlaylist
366             state:
367               version: '0.2'
368             listitems:
369             - !!python/object:hooke.curve.Curve
370               path: /path/to/curve/one
371             - !!python/object:hooke.curve.Curve
372               path: /path/to/curve/two
373
374         Relative paths are interpreted relative to the location of the
375         playlist file.
376
377         Examples
378         --------
379
380         >>> from .engine import CommandMessage
381
382         >>> root_path = os.path.sep + 'path'
383         >>> p = FilePlaylist(drivers=[],
384         ...                  path=os.path.join(root_path, 'to','playlist'))
385         >>> p.info['note'] = 'An example playlist'
386         >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'one'))
387         >>> c.info['note'] = 'The first curve'
388         >>> p.append_curve(c)
389         >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'two'))
390         >>> c.info['attr with spaces'] = 'The second curve\\nwith endlines'
391         >>> c.command_stack.extend([
392         ...         CommandMessage('command A', {'arg 0':0, 'arg 1':'X'}),
393         ...         CommandMessage('command B', {'arg 0':1, 'curve':c}),
394         ...         ])
395         >>> p.append_curve(c)
396         >>> print p.flatten()  # doctest: +REPORT_UDIFF
397         # Hooke playlist version 0.2
398         !!python/object/new:hooke.playlist.FilePlaylist
399         listitems:
400         - !!python/object:hooke.curve.Curve
401           info: {note: The first curve}
402           name: one
403           path: curve/one
404         - &id001 !!python/object:hooke.curve.Curve
405           command_stack: !!python/object/new:hooke.command_stack.CommandStack
406             listitems:
407             - !!python/object:hooke.engine.CommandMessage
408               arguments: {arg 0: 0, arg 1: X}
409               command: command A
410               explicit_user_call: true
411             - !!python/object:hooke.engine.CommandMessage
412               arguments:
413                 arg 0: 1
414                 curve: *id001
415               command: command B
416               explicit_user_call: true
417           info: {attr with spaces: 'The second curve
418         <BLANKLINE>
419               with endlines'}
420           name: two
421           path: curve/two
422         state:
423           _base_path: /path/to
424           info: {note: An example playlist}
425           name: playlist.hkp
426           path: /path/to/playlist.hkp
427           version: '0.2'
428         <BLANKLINE>
429         >>> p.relative_curve_paths = False
430         >>> print p.flatten()  # doctest: +REPORT_UDIFF
431         # Hooke playlist version 0.2
432         !!python/object/new:hooke.playlist.FilePlaylist
433         listitems:
434         - !!python/object:hooke.curve.Curve
435           info: {note: The first curve}
436           name: one
437           path: /path/to/curve/one
438         - &id001 !!python/object:hooke.curve.Curve
439           command_stack: !!python/object/new:hooke.command_stack.CommandStack
440             listitems:
441             - !!python/object:hooke.engine.CommandMessage
442               arguments: {arg 0: 0, arg 1: X}
443               command: command A
444               explicit_user_call: true
445             - !!python/object:hooke.engine.CommandMessage
446               arguments:
447                 arg 0: 1
448                 curve: *id001
449               command: command B
450               explicit_user_call: true
451           info: {attr with spaces: 'The second curve
452         <BLANKLINE>
453               with endlines'}
454           name: two
455           path: /path/to/curve/two
456         state:
457           _base_path: /path/to
458           info: {note: An example playlist}
459           name: playlist.hkp
460           path: /path/to/playlist.hkp
461           relative_curve_paths: false
462           version: '0.2'
463         <BLANKLINE>
464         """
465         rcp = self._relative_curve_paths
466         self._relative_curve_paths = self.relative_curve_paths
467         self.update_curve_paths()
468         self._relative_curve_paths = rcp
469         digest = self._digest
470         self._digest = None  # don't save the digest (recursive file).
471         yaml_string = yaml.dump(self, allow_unicode=True)
472         self._digest = digest
473         self.update_curve_paths()
474         return ('# Hooke playlist version %s\n' % self.version) + yaml_string
475
476     def save(self, path=None, makedirs=True):
477         """Saves the playlist to a YAML file.
478         """
479         self.set_path(path)
480         dirname = os.path.dirname(self.path) or '.'
481         if makedirs == True and not os.path.isdir(dirname):
482             os.makedirs(dirname)
483         with open(self.path, 'w') as f:
484             f.write(self.flatten())
485             self._digest = self.digest()
486
487
488 def from_string(string):
489     u"""Load a playlist from a string.
490
491     Examples
492     --------
493
494     Minimal example.
495
496     >>> string = '''# Hooke playlist version 0.2
497     ... !!python/object/new:hooke.playlist.FilePlaylist
498     ... state:
499     ...   version: '0.2'
500     ... listitems:
501     ... - !!python/object:hooke.curve.Curve
502     ...   path: curve/one
503     ... - !!python/object:hooke.curve.Curve
504     ...   path: curve/two
505     ... '''
506     >>> p = from_string(string)
507     >>> p.set_path('/path/to/playlist')
508     >>> for curve in p:
509     ...     print curve.name, curve.path
510     one /path/to/curve/one
511     two /path/to/curve/two
512
513     More complicated example.
514
515     >>> string = '''# Hooke playlist version 0.2
516     ... !!python/object/new:hooke.playlist.FilePlaylist
517     ... listitems:
518     ... - !!python/object:hooke.curve.Curve
519     ...   info: {note: The first curve}
520     ...   name: one
521     ...   path: /path/to/curve/one
522     ... - &id001 !!python/object:hooke.curve.Curve
523     ...   command_stack: !!python/object/new:hooke.command_stack.CommandStack
524     ...     listitems:
525     ...     - !!python/object:hooke.engine.CommandMessage
526     ...       arguments: {arg 0: 0, arg 1: X}
527     ...       command: command A
528     ...     - !!python/object:hooke.engine.CommandMessage
529     ...       arguments:
530     ...         arg 0: 1
531     ...         curve: *id001
532     ...       command: command B
533     ...   info: {attr with spaces: 'The second curve
534     ... 
535     ...       with endlines'}
536     ...   name: two
537     ...   path: /path/to/curve/two
538     ... state:
539     ...   _base_path: /path/to
540     ...   _index: 1
541     ...   info: {note: An example playlist}
542     ...   name: playlist.hkp
543     ...   path: /path/to/playlist.hkp
544     ...   version: '0.2'
545     ... '''
546     >>> p = from_string(string)
547     >>> p.set_path('/path/to/playlist')
548     >>> p._index
549     1
550     >>> p.info
551     {'note': 'An example playlist'}
552     >>> for curve in p:
553     ...     print curve.name, curve.path
554     one /path/to/curve/one
555     two /path/to/curve/two
556     >>> p[-1].info['attr with spaces']
557     'The second curve\\nwith endlines'
558     >>> type(p[-1].command_stack)
559     <class 'hooke.command_stack.CommandStack'>
560     >>> p[0].command_stack
561     []
562     >>> type(p[0].command_stack)
563     <class 'hooke.command_stack.CommandStack'>
564     >>> p[-1].command_stack  # doctest: +NORMALIZE_WHITESPACE
565     [<CommandMessage command A {arg 0: 0, arg 1: X}>,
566      <CommandMessage command B {arg 0: 1, curve: <Curve two>}>]
567     >>> type(p[1].command_stack)
568     <class 'hooke.command_stack.CommandStack'>
569     >>> c2 = p[-1]
570     >>> c2.command_stack[-1].arguments['curve'] == c2
571     True
572     """
573     return yaml.load(string)
574
575 def load(path=None, drivers=None, identify=True, hooke=None):
576     """Load a playlist from a file.
577     """
578     path = os.path.expanduser(playlist_path(path))
579     with open(path, 'r') as f:
580         text = f.read()
581     playlist = from_string(text)
582     playlist.set_path(path)
583     playlist._digest = playlist.digest()
584     if drivers != None:
585         playlist.drivers = drivers
586     playlist.set_path(path)
587     for curve in playlist:
588         curve.set_hooke(hooke)
589         if identify == True:
590             curve.identify(playlist.drivers)
591     return playlist
592
593
594 class Playlists (NoteIndexList):
595     """A :class:`NoteIndexList` of :class:`FilePlaylist`\s.
596     """
597     pass