Ran update-copyright.py
[hooke.git] / hooke / plugin / playlist.py
index 2b9caa8e29149c91b474282e7946c315d9cf6b79..ca800ee5a653f892c7b1f5addca51ae4dbc61820 100644 (file)
@@ -1,20 +1,19 @@
-# Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
+# Copyright (C) 2010-2012 W. Trevor King <wking@tremily.us>
 #
 # This file is part of Hooke.
 #
-# Hooke is free software: you can redistribute it and/or modify it
-# under the terms of the GNU Lesser General Public License as
-# published by the Free Software Foundation, either version 3 of the
-# License, or (at your option) any later version.
+# Hooke is free software: you can redistribute it and/or modify it under the
+# terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation, either version 3 of the License, or (at your option) any
+# later version.
 #
-# Hooke is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
-# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General
-# Public License for more details.
+# Hooke is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
+# details.
 #
-# You should have received a copy of the GNU Lesser General Public
-# License along with Hooke.  If not, see
-# <http://www.gnu.org/licenses/>.
+# You should have received a copy of the GNU Lesser General Public License
+# along with Hooke.  If not, see <http://www.gnu.org/licenses/>.
 
 """The ``playlist`` module provides :class:`PlaylistPlugin` and
 several associated :class:`hooke.command.Command`\s for handling
@@ -26,8 +25,9 @@ import logging
 import os.path
 
 from ..command import Command, Argument, Failure
-from ..playlist import FilePlaylist
 from ..curve import NotRecognized
+from ..playlist import load
+from ..util.itertools import reverse_enumerate
 from . import Builtin
 
 
@@ -37,9 +37,9 @@ class PlaylistPlugin (Builtin):
         self._commands = [
             NextCommand(self), PreviousCommand(self), JumpCommand(self),
             GetCommand(self), IndexCommand(self), CurveListCommand(self),
-            SaveCommand(self), LoadCommand(self),
+            NameCommand(self), SaveCommand(self), LoadCommand(self),
             AddCommand(self), AddGlobCommand(self),
-            RemoveCommand(self), ApplyCommandStack(self),
+            RemoveCommand(self), ApplyCommand(self),
             FilterCommand(self),
             ]
 
@@ -127,7 +127,9 @@ class PlaylistAddingCommand (Command):
     def _set_playlist(self, hooke, params, playlist):
         """Attach a new playlist.
         """
-        playlist.name = params['output playlist']
+        playlist_names = [p.name for p in hooke.playlists]
+        if playlist.name in playlist_names or playlist.name == None:
+            playlist.name = params['output playlist']  # HACK: override input name.  How to tell if it is callback-generated?
         hooke.playlists.append(playlist)
 
 
@@ -207,6 +209,26 @@ class CurveListCommand (PlaylistCommand):
        outqueue.put(list(self._playlist(hooke, params)))
 
 
+class NameCommand (PlaylistCommand):
+    """(Re)name a playlist.
+    """
+    def __init__(self, plugin):
+        super(NameCommand, self).__init__(
+            name='name playlist',
+            arguments=[
+                Argument(name='name', type='string', optional=False,
+                         help="""
+Name for the playlist.
+""".strip()),
+                ],
+            help=self.__doc__, plugin=plugin)
+
+    def _run(self, hooke, inqueue, outqueue, params):
+       p = self._playlist(hooke, params)
+        p.name = params['name']
+        outqueue.put(p)
+
+
 class SaveCommand (PlaylistCommand):
     """Save a playlist.
     """
@@ -247,11 +269,7 @@ Drivers for loading curves.
             help=self.__doc__, plugin=plugin)
 
     def _run(self, hooke, inqueue, outqueue, params):
-        p = FilePlaylist(drivers=params['drivers'], path=params['input'])
-        p.load(hooke=hooke)
-        playlist_names = [playlist.name for playlist in hooke.playlists]
-        if p.name in playlist_names or p.name == None:
-            p.name = params['output playlist']  # HACK: override input name.  How to tell if it is callback-generated?
+        p = load(path=params['input'], drivers=params['drivers'], hooke=hooke)
         self._set_playlist(hooke, params, p)
        outqueue.put(p)
 
@@ -303,7 +321,7 @@ Additional information for the input :class:`hooke.curve.Curve`.
 
     def _run(self, hooke, inqueue, outqueue, params):
         p = self._playlist(hooke, params)
-        for path in sorted(glob.glob(params['input'])):
+        for path in sorted(glob.glob(os.path.expanduser(params['input']))):
             try:
                 p.append_curve_by_path(path, params['info'], hooke=hooke)
             except NotRecognized, e:
@@ -319,30 +337,35 @@ class RemoveCommand (PlaylistCommand):
         super(RemoveCommand, self).__init__(
             name='remove curve from playlist',
             arguments=[
-                Argument(name='index', type='int', optional=False, help="""
+                Argument(name='index', type='int', optional=True, help="""
 Index of target curve.
 """.strip()),
                 ],
             help=self.__doc__, plugin=plugin)
 
     def _run(self, hooke, inqueue, outqueue, params):
-        self._playlist(hooke, params).pop(params['index'])
-        self._playlist(hooke, params).jump(params.index())
+        playlist = self._playlist(hooke, params)
+        if params['index'] is None:
+            params['index'] = playlist.index()
+        curve = playlist.pop(params['index'])
+        playlist.jump(playlist.index())
+        outqueue.put(curve)
 
 
-class ApplyCommandStack (PlaylistCommand):
+class ApplyCommand (PlaylistCommand):
     """Apply a :class:`~hooke.command_stack.CommandStack` to each
     curve in a playlist.
 
     TODO: discuss `evaluate`.
     """
     def __init__(self, plugin):
-        super(ApplyCommandStack, self).__init__(
-            name='apply command stack',
+        super(ApplyCommand, self).__init__(
+            name='apply command stack to playlist',
             arguments=[
-                Argument(name='commands', type='command stack', optional=False,
+                Argument(name='commands', type='command stack',
                          help="""
-Command stack to apply to each curve.
+Command stack to apply to each curve.  Defaults to the `command_stack`
+plugin's current stack.
 """.strip()),
                 Argument(name='evaluate', type='bool', default=False,
                          help="""
@@ -352,18 +375,27 @@ Evaluate the applied command stack immediately.
             help=self.__doc__, plugin=plugin)
 
     def _run(self, hooke, inqueue, outqueue, params):
-        if len(params['commands']) == 0:
-            return
+        params = self._setup_params(hooke=hooke, params=params)
         p = self._playlist(hooke, params)
         if params['evaluate'] == True:
+            exec_cmd = hooke.command_by_name['execute command stack']
             for curve in p.items():
-                for command in params['commands']:
-                    curve.command_stack.execute_command(hooke, command)
-                    curve.command_stack.append(command)
+                hooke.run_command(exec_cmd.name,
+                                  {'commands':params['commands'],
+                                   'stack':True})
         else:
             for curve in p:
-                curve.command_stack.extend(params['commands'])
-                curve.unload()  # force command stack execution on next access.
+                for command in params['commands']:
+                    curve.command_stack.append(command)
+                curve.set_hooke(hooke)
+                p.unload(curve)
+
+    def _setup_params(self, hooke, params):
+        if params['commands'] == None:
+            cstack_plugin = [p for p in hooke.plugins
+                             if p.name == 'command_stack'][0]
+            params['commands'] = cstack_plugin.command_stack
+        return params
 
 
 class FilterCommand (PlaylistAddingCommand, PlaylistCommand):
@@ -383,9 +415,10 @@ class FilterCommand (PlaylistAddingCommand, PlaylistCommand):
     method of their subclass.  See, for example,
     :meth:`NoteFilterCommand.filter`.
     """
-    def __init__(self, plugin, name='filter playlist'):
+    def __init__(self, plugin, name='filter playlist', load_curves=True):
         super(FilterCommand, self).__init__(
             name=name, help=self.__doc__, plugin=plugin)
+        self._load_curves = load_curves
         if not hasattr(self, 'filter'):
             self.arguments.append(
                 Argument(name='filter', type='function', optional=False,
@@ -399,10 +432,10 @@ Function returning `True` for "good" curves.
             filter_fn = params['filter']
         else:
             filter_fn = self.filter
-        p = self._playlist(hooke, params).filter(filter_fn,
+        p = self._playlist(hooke, params).filter(
+            filter_fn, load_curves=self._load_curves,
             hooke=hooke, inqueue=inqueue, outqueue=outqueue, params=params)
-        p.name = params['name']
+        self._set_playlist(hooke, params, p)
         if hasattr(p, 'path') and p.path != None:
             p.set_path(os.path.join(os.path.dirname(p.path), p.name))
-        self._set_playlist(hooke, params, p)
         outqueue.put(p)