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, expand=False):
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'):
233 path = os.path.abspath(os.path.expanduser(path))
237 class FilePlaylist (Playlist):
238 """A file-backed :class:`Playlist`.
243 >>> p = FilePlaylist(drivers=['Driver A', 'Driver B'])
244 >>> p.append(Curve('dummy/path/A'))
245 >>> p.append(Curve('dummy/path/B'))
247 The data-type is pickleable, to ensure we can move it between
248 processes with :class:`multiprocessing.Queue`\s.
251 >>> s = pickle.dumps(p)
252 >>> z = pickle.loads(s)
258 ['Driver A', 'Driver B']
260 The data-type is also YAMLable (see :mod:`hooke.util.yaml`).
269 ['Driver A', 'Driver B']
273 def __init__(self, drivers, name=None, path=None):
274 super(FilePlaylist, self).__init__(drivers, name)
275 self.path = self._base_path = None
277 self.relative_curve_paths = True
278 self._relative_curve_paths = False
280 def _set_default_attrs(self):
281 super(FilePlaylist, self)._set_default_attrs()
282 self._default_attrs['relative_curve_paths'] = True
283 self._default_attrs['_relative_curve_paths'] = False
284 self._default_attrs['_digest'] = None
286 def __getstate__(self):
287 state = super(FilePlaylist, self).__getstate__()
288 assert 'version' not in state, state
289 state['version'] = self.version
292 def __setstate__(self, state):
293 if 'version' in state:
294 version = state.pop('version')
295 assert version == FilePlaylist.version, (
296 'invalid version %s (%s) != %s (%s)'
297 % (version, type(version),
298 FilePlaylist.version, type(FilePlaylist.version)))
299 super(FilePlaylist, self).__setstate__(state)
301 def set_path(self, path):
302 orig_base_path = getattr(self, '_base_path', None)
304 if self._base_path == None:
305 self._base_path = os.getcwd()
307 path = playlist_path(path, expand=True)
309 self._base_path = os.path.dirname(self.path)
310 if self.name == None:
311 self.name = os.path.basename(path)
312 if self._base_path != orig_base_path:
313 self.update_curve_paths()
315 def update_curve_paths(self):
317 curve.set_path(self._curve_path(curve.path))
319 def _curve_path(self, path):
320 if self._base_path == None:
321 self._base_path = os.getcwd()
322 path = os.path.join(self._base_path, path)
323 if self._relative_curve_paths == True:
324 path = os.path.relpath(path, self._base_path)
327 def append_curve(self, curve):
328 curve.set_path(self._curve_path(curve.path))
329 super(FilePlaylist, self).append_curve(curve)
331 def append_curve_by_path(self, path, *args, **kwargs):
332 path = self._curve_path(path)
333 super(FilePlaylist, self).append_curve_by_path(path, *args, **kwargs)
336 return self.digest() == self._digest
339 r"""Compute the sha1 digest of the flattened playlist
345 >>> root_path = os.path.sep + 'path'
346 >>> p = FilePlaylist(drivers=[],
347 ... path=os.path.join(root_path, 'to','playlist'))
348 >>> p.info['note'] = 'An example playlist'
349 >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'one'))
350 >>> c.info['note'] = 'The first curve'
351 >>> p.append_curve(c)
352 >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'two'))
353 >>> c.info['note'] = 'The second curve'
354 >>> p.append_curve(c)
356 'f\xe26i\xb98i\x1f\xb61J7:\xf2\x8e\x1d\xde\xc3}g'
358 string = self.flatten()
359 return hashlib.sha1(string).digest()
362 """Create a string representation of the playlist.
364 A playlist is a YAML document with the following minimal syntax::
366 !!python/object/new:hooke.playlist.FilePlaylist
370 - !!python/object:hooke.curve.Curve
371 path: /path/to/curve/one
372 - !!python/object:hooke.curve.Curve
373 path: /path/to/curve/two
375 Relative paths are interpreted relative to the location of the
381 >>> from .engine import CommandMessage
383 >>> root_path = os.path.sep + 'path'
384 >>> p = FilePlaylist(drivers=[],
385 ... path=os.path.join(root_path, 'to','playlist'))
386 >>> p.info['note'] = 'An example playlist'
387 >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'one'))
388 >>> c.info['note'] = 'The first curve'
389 >>> p.append_curve(c)
390 >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'two'))
391 >>> c.info['attr with spaces'] = 'The second curve\\nwith endlines'
392 >>> c.command_stack.extend([
393 ... CommandMessage('command A', {'arg 0':0, 'arg 1':'X'}),
394 ... CommandMessage('command B', {'arg 0':1, 'curve':c}),
396 >>> p.append_curve(c)
397 >>> print p.flatten() # doctest: +REPORT_UDIFF
398 # Hooke playlist version 0.2
399 !!python/object/new:hooke.playlist.FilePlaylist
401 - !!python/object:hooke.curve.Curve
402 info: {note: The first curve}
405 - &id001 !!python/object:hooke.curve.Curve
406 command_stack: !!python/object/new:hooke.command_stack.CommandStack
408 - !!python/object:hooke.engine.CommandMessage
409 arguments: {arg 0: 0, arg 1: X}
411 explicit_user_call: true
412 - !!python/object:hooke.engine.CommandMessage
417 explicit_user_call: true
418 info: {attr with spaces: 'The second curve
425 info: {note: An example playlist}
427 path: /path/to/playlist.hkp
430 >>> p.relative_curve_paths = False
431 >>> print p.flatten() # doctest: +REPORT_UDIFF
432 # Hooke playlist version 0.2
433 !!python/object/new:hooke.playlist.FilePlaylist
435 - !!python/object:hooke.curve.Curve
436 info: {note: The first curve}
438 path: /path/to/curve/one
439 - &id001 !!python/object:hooke.curve.Curve
440 command_stack: !!python/object/new:hooke.command_stack.CommandStack
442 - !!python/object:hooke.engine.CommandMessage
443 arguments: {arg 0: 0, arg 1: X}
445 explicit_user_call: true
446 - !!python/object:hooke.engine.CommandMessage
451 explicit_user_call: true
452 info: {attr with spaces: 'The second curve
456 path: /path/to/curve/two
459 info: {note: An example playlist}
461 path: /path/to/playlist.hkp
462 relative_curve_paths: false
466 rcp = self._relative_curve_paths
467 self._relative_curve_paths = self.relative_curve_paths
468 self.update_curve_paths()
469 self._relative_curve_paths = rcp
470 digest = self._digest
471 self._digest = None # don't save the digest (recursive file).
472 yaml_string = yaml.dump(self, allow_unicode=True)
473 self._digest = digest
474 self.update_curve_paths()
475 return ('# Hooke playlist version %s\n' % self.version) + yaml_string
477 def save(self, path=None, makedirs=True):
478 """Saves the playlist to a YAML file.
481 dirname = os.path.dirname(self.path) or '.'
482 if makedirs == True and not os.path.isdir(dirname):
484 with open(self.path, 'w') as f:
485 f.write(self.flatten())
486 self._digest = self.digest()
489 def from_string(string):
490 u"""Load a playlist from a string.
497 >>> string = '''# Hooke playlist version 0.2
498 ... !!python/object/new:hooke.playlist.FilePlaylist
502 ... - !!python/object:hooke.curve.Curve
504 ... - !!python/object:hooke.curve.Curve
507 >>> p = from_string(string)
508 >>> p.set_path('/path/to/playlist')
510 ... print curve.name, curve.path
511 one /path/to/curve/one
512 two /path/to/curve/two
514 More complicated example.
516 >>> string = '''# Hooke playlist version 0.2
517 ... !!python/object/new:hooke.playlist.FilePlaylist
519 ... - !!python/object:hooke.curve.Curve
520 ... info: {note: The first curve}
522 ... path: /path/to/curve/one
523 ... - &id001 !!python/object:hooke.curve.Curve
524 ... command_stack: !!python/object/new:hooke.command_stack.CommandStack
526 ... - !!python/object:hooke.engine.CommandMessage
527 ... arguments: {arg 0: 0, arg 1: X}
528 ... command: command A
529 ... - !!python/object:hooke.engine.CommandMessage
533 ... command: command B
534 ... info: {attr with spaces: 'The second curve
538 ... path: /path/to/curve/two
540 ... _base_path: /path/to
542 ... info: {note: An example playlist}
543 ... name: playlist.hkp
544 ... path: /path/to/playlist.hkp
547 >>> p = from_string(string)
548 >>> p.set_path('/path/to/playlist')
552 {'note': 'An example playlist'}
554 ... print curve.name, curve.path
555 one /path/to/curve/one
556 two /path/to/curve/two
557 >>> p[-1].info['attr with spaces']
558 'The second curve\\nwith endlines'
559 >>> type(p[-1].command_stack)
560 <class 'hooke.command_stack.CommandStack'>
561 >>> p[0].command_stack
563 >>> type(p[0].command_stack)
564 <class 'hooke.command_stack.CommandStack'>
565 >>> p[-1].command_stack # doctest: +NORMALIZE_WHITESPACE
566 [<CommandMessage command A {arg 0: 0, arg 1: X}>,
567 <CommandMessage command B {arg 0: 1, curve: <Curve two>}>]
568 >>> type(p[1].command_stack)
569 <class 'hooke.command_stack.CommandStack'>
571 >>> c2.command_stack[-1].arguments['curve'] == c2
574 return yaml.load(string)
576 def load(path=None, drivers=None, identify=True, hooke=None):
577 """Load a playlist from a file.
579 path = playlist_path(path, expand=True)
580 with open(path, 'r') as f:
582 playlist = from_string(text)
583 playlist.set_path(path)
584 playlist._digest = playlist.digest()
586 playlist.drivers = drivers
587 playlist.set_path(path)
588 for curve in playlist:
589 curve.set_hooke(hooke)
591 curve.identify(playlist.drivers)
595 class Playlists (NoteIndexList):
596 """A :class:`NoteIndexList` of :class:`FilePlaylist`\s.