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