1 # Copyright (C) 2010-2011 W. Trevor King <wking@drexel.edu>
3 # This file is part of Hooke.
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.
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.
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/>.
19 """The `playlist` module provides a :class:`Playlist` and its subclass
20 :class:`FilePlaylist` for manipulating lists of
21 :class:`hooke.curve.Curve`\s.
31 from yaml.representer import RepresenterError
33 from .command_stack import CommandStack
34 from .curve import Curve
35 from .util.itertools import reverse_enumerate
38 class NoteIndexList (list):
39 """A list that keeps track of a "current" item and additional notes.
41 :attr:`index` (i.e. "bookmark") is the index of the currently
42 current curve. Also keep a :class:`dict` of additional information
45 def __init__(self, name=None):
46 super(NoteIndexList, self).__init__()
47 self._set_default_attrs()
48 self.__setstate__({'name': name})
51 return str(self.__unicode__())
53 def __unicode__(self):
54 return u'<%s %s>' % (self.__class__.__name__, self.name)
59 def _set_default_attrs(self):
60 self._default_attrs = {
66 def __getstate__(self):
67 return self.__dict__.copy()
69 def __setstate__(self, state):
70 self._set_default_attrs()
73 self.__dict__.update(self._default_attrs)
75 self.__dict__.update(state)
77 print state, type(state), e
78 if self.info in [None, {}]:
81 def _setup_item(self, item):
82 """Perform any required initialization before returning an item.
86 def index(self, value=None, *args, **kwargs):
87 """Extend `list.index`, returning the current index if `value`
92 return super(NoteIndexList, self).index(value, *args, **kwargs)
94 def current(self, load=True):
97 item = self[self._index]
99 self._setup_item(item)
102 def jump(self, index):
106 self._index = index % len(self)
109 self.jump(self._index + 1)
112 self.jump(self._index - 1)
114 def items(self, reverse=False):
115 """Iterate through `self` calling `_setup_item` on each item
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
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)
135 items = enumerate(self)
138 self._setup_item(item)
142 def filter(self, keeper_fn=lambda item:True, load_curves=True,
145 if load_curves == True:
146 items = self.items(reverse=True)
148 items = reversed(self)
150 if keeper_fn(item, *args, **kwargs) != True:
152 try: # attempt to maintain the same current item
153 c._index = c.index(self.current())
159 class Playlist (NoteIndexList):
160 """A :class:`NoteIndexList` of :class:`hooke.Curve`\s.
162 Keeps a list of :attr:`drivers` for loading curves.
164 def __init__(self, drivers, name=None):
165 super(Playlist, self).__init__(name=name)
166 self.drivers = drivers
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.
175 def __setstate__(self, state):
176 super(Playlist, self).__setstate__(state)
177 if self.drivers in [None, {}]:
179 if self._loaded in [None, {}]:
182 def append_curve(self, curve):
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)
190 c.identify(self.drivers)
194 def _setup_item(self, curve):
195 if curve != None and curve not in self._loaded:
196 if curve not in self:
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:
202 self._loaded.append(curve)
203 if len(self._loaded) > self._max_loaded:
204 oldest = self._loaded.pop(0)
207 def unload(self, curve):
208 "Inverse of `._setup_item`."
211 self._loaded.remove(curve)
216 def playlist_path(path):
217 """Normalize playlist path extensions.
221 >>> print playlist_path('playlist')
223 >>> print playlist_path('playlist.hkp')
225 >>> print playlist_path(None)
230 if not path.endswith('.hkp'):
235 class FilePlaylist (Playlist):
236 """A file-backed :class:`Playlist`.
241 >>> p = FilePlaylist(drivers=['Driver A', 'Driver B'])
242 >>> p.append(Curve('dummy/path/A'))
243 >>> p.append(Curve('dummy/path/B'))
245 The data-type is pickleable, to ensure we can move it between
246 processes with :class:`multiprocessing.Queue`\s.
249 >>> s = pickle.dumps(p)
250 >>> z = pickle.loads(s)
256 ['Driver A', 'Driver B']
258 The data-type is also YAMLable (see :mod:`hooke.util.yaml`).
267 ['Driver A', 'Driver B']
271 def __init__(self, drivers, name=None, path=None):
272 super(FilePlaylist, self).__init__(drivers, name)
273 self.path = self._base_path = None
275 self.relative_curve_paths = True
276 self._relative_curve_paths = False
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
284 def __getstate__(self):
285 state = super(FilePlaylist, self).__getstate__()
286 assert 'version' not in state, state
287 state['version'] = self.version
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)
299 def set_path(self, path):
300 orig_base_path = getattr(self, '_base_path', None)
302 if self._base_path == None:
303 self._base_path = os.getcwd()
305 path = playlist_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()
314 def update_curve_paths(self):
316 curve.set_path(self._curve_path(curve.path))
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)
326 def append_curve(self, curve):
327 curve.set_path(self._curve_path(curve.path))
328 super(FilePlaylist, self).append_curve(curve)
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)
335 return self.digest() == self._digest
338 r"""Compute the sha1 digest of the flattened playlist
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)
355 'f\xe26i\xb98i\x1f\xb61J7:\xf2\x8e\x1d\xde\xc3}g'
357 string = self.flatten()
358 return hashlib.sha1(string).digest()
361 """Create a string representation of the playlist.
363 A playlist is a YAML document with the following minimal syntax::
365 !!python/object/new:hooke.playlist.FilePlaylist
369 - !!python/object:hooke.curve.Curve
370 path: /path/to/curve/one
371 - !!python/object:hooke.curve.Curve
372 path: /path/to/curve/two
374 Relative paths are interpreted relative to the location of the
380 >>> from .engine import CommandMessage
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}),
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
400 - !!python/object:hooke.curve.Curve
401 info: {note: The first curve}
404 - &id001 !!python/object:hooke.curve.Curve
405 command_stack: !!python/object/new:hooke.command_stack.CommandStack
407 - !!python/object:hooke.engine.CommandMessage
408 arguments: {arg 0: 0, arg 1: X}
410 explicit_user_call: true
411 - !!python/object:hooke.engine.CommandMessage
416 explicit_user_call: true
417 info: {attr with spaces: 'The second curve
424 info: {note: An example playlist}
426 path: /path/to/playlist.hkp
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
434 - !!python/object:hooke.curve.Curve
435 info: {note: The first curve}
437 path: /path/to/curve/one
438 - &id001 !!python/object:hooke.curve.Curve
439 command_stack: !!python/object/new:hooke.command_stack.CommandStack
441 - !!python/object:hooke.engine.CommandMessage
442 arguments: {arg 0: 0, arg 1: X}
444 explicit_user_call: true
445 - !!python/object:hooke.engine.CommandMessage
450 explicit_user_call: true
451 info: {attr with spaces: 'The second curve
455 path: /path/to/curve/two
458 info: {note: An example playlist}
460 path: /path/to/playlist.hkp
461 relative_curve_paths: false
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
476 def save(self, path=None, makedirs=True):
477 """Saves the playlist to a YAML file.
480 dirname = os.path.dirname(self.path) or '.'
481 if makedirs == True and not os.path.isdir(dirname):
483 with open(self.path, 'w') as f:
484 f.write(self.flatten())
485 self._digest = self.digest()
488 def from_string(string):
489 u"""Load a playlist from a string.
496 >>> string = '''# Hooke playlist version 0.2
497 ... !!python/object/new:hooke.playlist.FilePlaylist
501 ... - !!python/object:hooke.curve.Curve
503 ... - !!python/object:hooke.curve.Curve
506 >>> p = from_string(string)
507 >>> p.set_path('/path/to/playlist')
509 ... print curve.name, curve.path
510 one /path/to/curve/one
511 two /path/to/curve/two
513 More complicated example.
515 >>> string = '''# Hooke playlist version 0.2
516 ... !!python/object/new:hooke.playlist.FilePlaylist
518 ... - !!python/object:hooke.curve.Curve
519 ... info: {note: The first curve}
521 ... path: /path/to/curve/one
522 ... - &id001 !!python/object:hooke.curve.Curve
523 ... command_stack: !!python/object/new:hooke.command_stack.CommandStack
525 ... - !!python/object:hooke.engine.CommandMessage
526 ... arguments: {arg 0: 0, arg 1: X}
527 ... command: command A
528 ... - !!python/object:hooke.engine.CommandMessage
532 ... command: command B
533 ... info: {attr with spaces: 'The second curve
537 ... path: /path/to/curve/two
539 ... _base_path: /path/to
541 ... info: {note: An example playlist}
542 ... name: playlist.hkp
543 ... path: /path/to/playlist.hkp
546 >>> p = from_string(string)
547 >>> p.set_path('/path/to/playlist')
551 {'note': 'An example playlist'}
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
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'>
570 >>> c2.command_stack[-1].arguments['curve'] == c2
573 return yaml.load(string)
575 def load(path=None, drivers=None, identify=True, hooke=None):
576 """Load a playlist from a file.
578 path = os.path.expanduser(playlist_path(path))
579 with open(path, 'r') as f:
581 playlist = from_string(text)
582 playlist.set_path(path)
583 playlist._digest = playlist.digest()
585 playlist.drivers = drivers
586 playlist.set_path(path)
587 for curve in playlist:
588 curve.set_hooke(hooke)
590 curve.identify(playlist.drivers)
594 class Playlists (NoteIndexList):
595 """A :class:`NoteIndexList` of :class:`FilePlaylist`\s.