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)
97 item = self[self._index]
98 self._setup_item(item)
101 def jump(self, index):
105 self._index = index % len(self)
108 self.jump(self._index + 1)
111 self.jump(self._index - 1)
113 def items(self, reverse=False):
114 """Iterate through `self` calling `_setup_item` on each item
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
129 items = reverse_enumerate(self)
131 items = enumerate(self)
134 self._setup_item(item)
138 def filter(self, keeper_fn=lambda item:True, load_curves=True,
140 c = copy.deepcopy(self)
141 if load_curves == True:
142 items = c.items(reverse=True)
146 if keeper_fn(item, *args, **kwargs) != True:
148 try: # attempt to maintain the same current item
149 c._index = c.index(self.current())
155 class Playlist (NoteIndexList):
156 """A :class:`NoteIndexList` of :class:`hooke.Curve`\s.
158 Keeps a list of :attr:`drivers` for loading curves.
160 def __init__(self, drivers, name=None):
161 super(Playlist, self).__init__(name=name)
162 self.drivers = drivers
163 self._max_loaded = 100 # curves to hold in memory simultaneously.
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
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 playlist_path(path):
205 """Normalize playlist path extensions.
209 >>> print playlist_path('playlist')
211 >>> print playlist_path('playlist.hkp')
213 >>> print playlist_path(None)
218 if not path.endswith('.hkp'):
223 class FilePlaylist (Playlist):
224 """A file-backed :class:`Playlist`.
229 >>> p = FilePlaylist(drivers=['Driver A', 'Driver B'])
230 >>> p.append(Curve('dummy/path/A'))
231 >>> p.append(Curve('dummy/path/B'))
233 The data-type is pickleable, to ensure we can move it between
234 processes with :class:`multiprocessing.Queue`\s.
237 >>> s = pickle.dumps(p)
238 >>> z = pickle.loads(s)
244 ['Driver A', 'Driver B']
246 The data-type is also YAMLable (see :mod:`hooke.util.yaml`).
255 ['Driver A', 'Driver B']
259 def __init__(self, drivers, name=None, path=None):
260 super(FilePlaylist, self).__init__(drivers, name)
261 self.path = self._base_path = None
263 self.relative_curve_paths = True
264 self._relative_curve_paths = False
266 def _set_default_attrs(self):
267 super(FilePlaylist, self)._set_default_attrs()
268 self._default_attrs['relative_curve_paths'] = True
269 self._default_attrs['_relative_curve_paths'] = False
270 self._default_attrs['_digest'] = None
272 def __getstate__(self):
273 state = super(FilePlaylist, self).__getstate__()
274 assert 'version' not in state, state
275 state['version'] = self.version
278 def __setstate__(self, state):
279 if 'version' in state:
280 version = state.pop('version')
281 assert version == FilePlaylist.version, (
282 'invalid version %s (%s) != %s (%s)'
283 % (version, type(version),
284 FilePlaylist.version, type(FilePlaylist.version)))
285 super(FilePlaylist, self).__setstate__(state)
287 def set_path(self, path):
288 orig_base_path = getattr(self, '_base_path', None)
290 if self._base_path == None:
291 self._base_path = os.getcwd()
293 path = playlist_path(path)
295 self._base_path = os.path.dirname(os.path.abspath(
296 os.path.expanduser(self.path)))
297 if self.name == None:
298 self.name = os.path.basename(path)
299 if self._base_path != orig_base_path:
300 self.update_curve_paths()
302 def update_curve_paths(self):
304 curve.set_path(self._curve_path(curve.path))
306 def _curve_path(self, path):
307 if self._base_path == None:
308 self._base_path = os.getcwd()
309 path = os.path.join(self._base_path, path)
310 if self._relative_curve_paths == True:
311 path = os.path.relpath(path, self._base_path)
314 def append_curve(self, curve):
315 curve.set_path(self._curve_path(curve.path))
316 super(FilePlaylist, self).append_curve(curve)
318 def append_curve_by_path(self, path, *args, **kwargs):
319 path = self._curve_path(path)
320 super(FilePlaylist, self).append_curve_by_path(path, *args, **kwargs)
323 return self.digest() == self._digest
326 r"""Compute the sha1 digest of the flattened playlist
332 >>> root_path = os.path.sep + 'path'
333 >>> p = FilePlaylist(drivers=[],
334 ... path=os.path.join(root_path, 'to','playlist'))
335 >>> p.info['note'] = 'An example playlist'
336 >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'one'))
337 >>> c.info['note'] = 'The first curve'
338 >>> p.append_curve(c)
339 >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'two'))
340 >>> c.info['note'] = 'The second curve'
341 >>> p.append_curve(c)
343 'f\xe26i\xb98i\x1f\xb61J7:\xf2\x8e\x1d\xde\xc3}g'
345 string = self.flatten()
346 return hashlib.sha1(string).digest()
349 """Create a string representation of the playlist.
351 A playlist is a YAML document with the following minimal syntax::
353 !!python/object/new:hooke.playlist.FilePlaylist
357 - !!python/object:hooke.curve.Curve
358 path: /path/to/curve/one
359 - !!python/object:hooke.curve.Curve
360 path: /path/to/curve/two
362 Relative paths are interpreted relative to the location of the
368 >>> from .engine import CommandMessage
370 >>> root_path = os.path.sep + 'path'
371 >>> p = FilePlaylist(drivers=[],
372 ... path=os.path.join(root_path, 'to','playlist'))
373 >>> p.info['note'] = 'An example playlist'
374 >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'one'))
375 >>> c.info['note'] = 'The first curve'
376 >>> p.append_curve(c)
377 >>> c = Curve(os.path.join(root_path, 'to', 'curve', 'two'))
378 >>> c.info['attr with spaces'] = 'The second curve\\nwith endlines'
379 >>> c.command_stack.extend([
380 ... CommandMessage('command A', {'arg 0':0, 'arg 1':'X'}),
381 ... CommandMessage('command B', {'arg 0':1, 'curve':c}),
383 >>> p.append_curve(c)
384 >>> print p.flatten() # doctest: +REPORT_UDIFF
385 # Hooke playlist version 0.2
386 !!python/object/new:hooke.playlist.FilePlaylist
388 - !!python/object:hooke.curve.Curve
389 info: {note: The first curve}
392 - &id001 !!python/object:hooke.curve.Curve
393 command_stack: !!python/object/new:hooke.command_stack.CommandStack
395 - !!python/object:hooke.engine.CommandMessage
396 arguments: {arg 0: 0, arg 1: X}
398 - !!python/object:hooke.engine.CommandMessage
403 info: {attr with spaces: 'The second curve
410 info: {note: An example playlist}
412 path: /path/to/playlist.hkp
415 >>> p.relative_curve_paths = False
416 >>> print p.flatten() # doctest: +REPORT_UDIFF
417 # Hooke playlist version 0.2
418 !!python/object/new:hooke.playlist.FilePlaylist
420 - !!python/object:hooke.curve.Curve
421 info: {note: The first curve}
423 path: /path/to/curve/one
424 - &id001 !!python/object:hooke.curve.Curve
425 command_stack: !!python/object/new:hooke.command_stack.CommandStack
427 - !!python/object:hooke.engine.CommandMessage
428 arguments: {arg 0: 0, arg 1: X}
430 - !!python/object:hooke.engine.CommandMessage
435 info: {attr with spaces: 'The second curve
439 path: /path/to/curve/two
442 info: {note: An example playlist}
444 path: /path/to/playlist.hkp
445 relative_curve_paths: false
449 rcp = self._relative_curve_paths
450 self._relative_curve_paths = self.relative_curve_paths
451 self.update_curve_paths()
452 self._relative_curve_paths = rcp
454 yaml_string = yaml.dump(self, allow_unicode=True)
455 self.update_curve_paths()
456 return ('# Hooke playlist version %s\n' % self.version) + yaml_string
458 def save(self, path=None, makedirs=True):
459 """Saves the playlist to a YAML file.
462 dirname = os.path.dirname(self.path) or '.'
463 if makedirs == True and not os.path.isdir(dirname):
465 with open(self.path, 'w') as f:
466 f.write(self.flatten())
467 self._digest = self.digest()
470 def from_string(string):
471 u"""Load a playlist from a string.
478 >>> string = '''# Hooke playlist version 0.2
479 ... !!python/object/new:hooke.playlist.FilePlaylist
483 ... - !!python/object:hooke.curve.Curve
485 ... - !!python/object:hooke.curve.Curve
488 >>> p = from_string(string)
489 >>> p.set_path('/path/to/playlist')
491 ... print curve.name, curve.path
492 one /path/to/curve/one
493 two /path/to/curve/two
495 More complicated example.
497 >>> string = '''# Hooke playlist version 0.2
498 ... !!python/object/new:hooke.playlist.FilePlaylist
500 ... - !!python/object:hooke.curve.Curve
501 ... info: {note: The first curve}
503 ... path: /path/to/curve/one
504 ... - &id001 !!python/object:hooke.curve.Curve
505 ... command_stack: !!python/object/new:hooke.command_stack.CommandStack
507 ... - !!python/object:hooke.engine.CommandMessage
508 ... arguments: {arg 0: 0, arg 1: X}
509 ... command: command A
510 ... - !!python/object:hooke.engine.CommandMessage
514 ... command: command B
515 ... info: {attr with spaces: 'The second curve
519 ... path: /path/to/curve/two
521 ... _base_path: /path/to
523 ... info: {note: An example playlist}
524 ... name: playlist.hkp
525 ... path: /path/to/playlist.hkp
528 >>> p = from_string(string)
529 >>> p.set_path('/path/to/playlist')
533 {'note': 'An example playlist'}
535 ... print curve.name, curve.path
536 one /path/to/curve/one
537 two /path/to/curve/two
538 >>> p[-1].info['attr with spaces']
539 'The second curve\\nwith endlines'
540 >>> type(p[-1].command_stack)
541 <class 'hooke.command_stack.CommandStack'>
542 >>> p[0].command_stack
544 >>> type(p[0].command_stack)
545 <class 'hooke.command_stack.CommandStack'>
546 >>> p[-1].command_stack # doctest: +NORMALIZE_WHITESPACE
547 [<CommandMessage command A {arg 0: 0, arg 1: X}>,
548 <CommandMessage command B {arg 0: 1, curve: <Curve two>}>]
549 >>> type(p[1].command_stack)
550 <class 'hooke.command_stack.CommandStack'>
552 >>> c2.command_stack[-1].arguments['curve'] == c2
555 return yaml.load(string)
557 def load(path=None, drivers=None, identify=True, hooke=None):
558 """Load a playlist from a file.
560 path = playlist_path(path)
561 with open(path, 'r') as f:
563 playlist = from_string(text)
564 playlist.set_path(path)
565 playlist._digest = playlist.digest()
567 playlist.drivers = drivers
568 playlist.set_path(path)
569 for curve in playlist:
570 curve.set_hooke(hooke)
572 curve.identify(playlist.drivers)
576 class Playlists (NoteIndexList):
577 """A :class:`NoteIndexList` of :class:`FilePlaylist`\s.