1 # Copyright (C) 2010 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 items = reverse_enumerate(self)
132 items = enumerate(self)
135 self._setup_item(item)
139 def filter(self, keeper_fn=lambda item:True, load_curves=True,
141 c = copy.deepcopy(self)
142 if load_curves == True:
143 items = c.items(reverse=True)
147 if keeper_fn(item, *args, **kwargs) != True:
149 try: # attempt to maintain the same current item
150 c._index = c.index(self.current())
156 class Playlist (NoteIndexList):
157 """A :class:`NoteIndexList` of :class:`hooke.Curve`\s.
159 Keeps a list of :attr:`drivers` for loading curves.
161 def __init__(self, drivers, name=None):
162 super(Playlist, self).__init__(name=name)
163 self.drivers = drivers
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 # curves to hold in memory simultaneously.
172 def __setstate__(self, state):
173 super(Playlist, self).__setstate__(state)
174 if self.drivers in [None, {}]:
176 if self._loaded in [None, {}]:
179 def append_curve(self, curve):
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)
187 c.identify(self.drivers)
191 def _setup_item(self, curve):
192 if curve != None and curve not in self._loaded:
193 if curve not in self:
195 if curve.driver == None:
196 c.identify(self.drivers)
197 if curve.data == None:
199 self._loaded.append(curve)
200 if len(self._loaded) > self._max_loaded:
201 oldest = self._loaded.pop(0)
204 def unload(self, curve):
205 "Inverse of .`_setup_item`."
208 self._loaded.remove(curve)
213 def playlist_path(path):
214 """Normalize playlist path extensions.
218 >>> print playlist_path('playlist')
220 >>> print playlist_path('playlist.hkp')
222 >>> print playlist_path(None)
227 if not path.endswith('.hkp'):
232 class FilePlaylist (Playlist):
233 """A file-backed :class:`Playlist`.
238 >>> p = FilePlaylist(drivers=['Driver A', 'Driver B'])
239 >>> p.append(Curve('dummy/path/A'))
240 >>> p.append(Curve('dummy/path/B'))
242 The data-type is pickleable, to ensure we can move it between
243 processes with :class:`multiprocessing.Queue`\s.
246 >>> s = pickle.dumps(p)
247 >>> z = pickle.loads(s)
253 ['Driver A', 'Driver B']
255 The data-type is also YAMLable (see :mod:`hooke.util.yaml`).
264 ['Driver A', 'Driver B']
268 def __init__(self, drivers, name=None, path=None):
269 super(FilePlaylist, self).__init__(drivers, name)
270 self.path = self._base_path = None
272 self.relative_curve_paths = True
273 self._relative_curve_paths = False
275 def _set_default_attrs(self):
276 super(FilePlaylist, self)._set_default_attrs()
277 self._default_attrs['relative_curve_paths'] = True
278 self._default_attrs['_relative_curve_paths'] = False
279 self._default_attrs['_digest'] = None
281 def __getstate__(self):
282 state = super(FilePlaylist, self).__getstate__()
283 assert 'version' not in state, state
284 state['version'] = self.version
287 def __setstate__(self, state):
288 if 'version' in state:
289 version = state.pop('version')
290 assert version == FilePlaylist.version, (
291 'invalid version %s (%s) != %s (%s)'
292 % (version, type(version),
293 FilePlaylist.version, type(FilePlaylist.version)))
294 super(FilePlaylist, self).__setstate__(state)
296 def set_path(self, path):
297 orig_base_path = getattr(self, '_base_path', None)
299 if self._base_path == None:
300 self._base_path = os.getcwd()
302 path = playlist_path(path)
304 self._base_path = os.path.dirname(os.path.abspath(
305 os.path.expanduser(self.path)))
306 if self.name == None:
307 self.name = os.path.basename(path)
308 if self._base_path != orig_base_path:
309 self.update_curve_paths()
311 def update_curve_paths(self):
313 curve.set_path(self._curve_path(curve.path))
315 def _curve_path(self, path):
316 if self._base_path == None:
317 self._base_path = os.getcwd()
318 path = os.path.join(self._base_path, path)
319 if self._relative_curve_paths == True:
320 path = os.path.relpath(path, self._base_path)
323 def append_curve(self, curve):
324 curve.set_path(self._curve_path(curve.path))
325 super(FilePlaylist, self).append_curve(curve)
327 def append_curve_by_path(self, path, *args, **kwargs):
328 path = self._curve_path(path)
329 super(FilePlaylist, self).append_curve_by_path(path, *args, **kwargs)
332 return self.digest() == self._digest
335 r"""Compute the sha1 digest of the flattened playlist
341 >>> root_path = os.path.sep + 'path'
342 >>> p = FilePlaylist(drivers=[],
343 ... path=os.path.join(root_path, 'to','playlist'))
344 >>> p.info['note'] = 'An example playlist'
345 >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'one'))
346 >>> c.info['note'] = 'The first curve'
347 >>> p.append_curve(c)
348 >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'two'))
349 >>> c.info['note'] = 'The second curve'
350 >>> p.append_curve(c)
352 'f\xe26i\xb98i\x1f\xb61J7:\xf2\x8e\x1d\xde\xc3}g'
354 string = self.flatten()
355 return hashlib.sha1(string).digest()
358 """Create a string representation of the playlist.
360 A playlist is a YAML document with the following minimal syntax::
362 !!python/object/new:hooke.playlist.FilePlaylist
366 - !!python/object:hooke.curve.Curve
367 path: /path/to/curve/one
368 - !!python/object:hooke.curve.Curve
369 path: /path/to/curve/two
371 Relative paths are interpreted relative to the location of the
377 >>> from .engine import CommandMessage
379 >>> root_path = os.path.sep + 'path'
380 >>> p = FilePlaylist(drivers=[],
381 ... path=os.path.join(root_path, 'to','playlist'))
382 >>> p.info['note'] = 'An example playlist'
383 >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'one'))
384 >>> c.info['note'] = 'The first curve'
385 >>> p.append_curve(c)
386 >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'two'))
387 >>> c.info['attr with spaces'] = 'The second curve\\nwith endlines'
388 >>> c.command_stack.extend([
389 ... CommandMessage('command A', {'arg 0':0, 'arg 1':'X'}),
390 ... CommandMessage('command B', {'arg 0':1, 'curve':c}),
392 >>> p.append_curve(c)
393 >>> print p.flatten() # doctest: +REPORT_UDIFF
394 # Hooke playlist version 0.2
395 !!python/object/new:hooke.playlist.FilePlaylist
397 - !!python/object:hooke.curve.Curve
398 info: {note: The first curve}
401 - &id001 !!python/object:hooke.curve.Curve
402 command_stack: !!python/object/new:hooke.command_stack.CommandStack
404 - !!python/object:hooke.engine.CommandMessage
405 arguments: {arg 0: 0, arg 1: X}
407 - !!python/object:hooke.engine.CommandMessage
412 info: {attr with spaces: 'The second curve
419 info: {note: An example playlist}
421 path: /path/to/playlist.hkp
424 >>> p.relative_curve_paths = False
425 >>> print p.flatten() # doctest: +REPORT_UDIFF
426 # Hooke playlist version 0.2
427 !!python/object/new:hooke.playlist.FilePlaylist
429 - !!python/object:hooke.curve.Curve
430 info: {note: The first curve}
432 path: /path/to/curve/one
433 - &id001 !!python/object:hooke.curve.Curve
434 command_stack: !!python/object/new:hooke.command_stack.CommandStack
436 - !!python/object:hooke.engine.CommandMessage
437 arguments: {arg 0: 0, arg 1: X}
439 - !!python/object:hooke.engine.CommandMessage
444 info: {attr with spaces: 'The second curve
448 path: /path/to/curve/two
451 info: {note: An example playlist}
453 path: /path/to/playlist.hkp
454 relative_curve_paths: false
458 rcp = self._relative_curve_paths
459 self._relative_curve_paths = self.relative_curve_paths
460 self.update_curve_paths()
461 self._relative_curve_paths = rcp
463 yaml_string = yaml.dump(self, allow_unicode=True)
464 self.update_curve_paths()
465 return ('# Hooke playlist version %s\n' % self.version) + yaml_string
467 def save(self, path=None, makedirs=True):
468 """Saves the playlist to a YAML file.
471 dirname = os.path.dirname(self.path) or '.'
472 if makedirs == True and not os.path.isdir(dirname):
474 with open(self.path, 'w') as f:
475 f.write(self.flatten())
476 self._digest = self.digest()
479 def from_string(string):
480 u"""Load a playlist from a string.
487 >>> string = '''# Hooke playlist version 0.2
488 ... !!python/object/new:hooke.playlist.FilePlaylist
492 ... - !!python/object:hooke.curve.Curve
494 ... - !!python/object:hooke.curve.Curve
497 >>> p = from_string(string)
498 >>> p.set_path('/path/to/playlist')
500 ... print curve.name, curve.path
501 one /path/to/curve/one
502 two /path/to/curve/two
504 More complicated example.
506 >>> string = '''# Hooke playlist version 0.2
507 ... !!python/object/new:hooke.playlist.FilePlaylist
509 ... - !!python/object:hooke.curve.Curve
510 ... info: {note: The first curve}
512 ... path: /path/to/curve/one
513 ... - &id001 !!python/object:hooke.curve.Curve
514 ... command_stack: !!python/object/new:hooke.command_stack.CommandStack
516 ... - !!python/object:hooke.engine.CommandMessage
517 ... arguments: {arg 0: 0, arg 1: X}
518 ... command: command A
519 ... - !!python/object:hooke.engine.CommandMessage
523 ... command: command B
524 ... info: {attr with spaces: 'The second curve
528 ... path: /path/to/curve/two
530 ... _base_path: /path/to
532 ... info: {note: An example playlist}
533 ... name: playlist.hkp
534 ... path: /path/to/playlist.hkp
537 >>> p = from_string(string)
538 >>> p.set_path('/path/to/playlist')
542 {'note': 'An example playlist'}
544 ... print curve.name, curve.path
545 one /path/to/curve/one
546 two /path/to/curve/two
547 >>> p[-1].info['attr with spaces']
548 'The second curve\\nwith endlines'
549 >>> type(p[-1].command_stack)
550 <class 'hooke.command_stack.CommandStack'>
551 >>> p[0].command_stack
553 >>> type(p[0].command_stack)
554 <class 'hooke.command_stack.CommandStack'>
555 >>> p[-1].command_stack # doctest: +NORMALIZE_WHITESPACE
556 [<CommandMessage command A {arg 0: 0, arg 1: X}>,
557 <CommandMessage command B {arg 0: 1, curve: <Curve two>}>]
558 >>> type(p[1].command_stack)
559 <class 'hooke.command_stack.CommandStack'>
561 >>> c2.command_stack[-1].arguments['curve'] == c2
564 return yaml.load(string)
566 def load(path=None, drivers=None, identify=True, hooke=None):
567 """Load a playlist from a file.
569 path = playlist_path(path)
570 with open(path, 'r') as f:
572 playlist = from_string(text)
573 playlist.set_path(path)
574 playlist._digest = playlist.digest()
576 playlist.drivers = drivers
577 playlist.set_path(path)
578 for curve in playlist:
579 curve.set_hooke(hooke)
581 curve.identify(playlist.drivers)
585 class Playlists (NoteIndexList):
586 """A :class:`NoteIndexList` of :class:`FilePlaylist`\s.