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 ``command_stack`` module provides tools for managing and
20 executing stacks of :class:`~hooke.engine.CommandMessage`\s.
24 class CommandStack (list):
25 """Store a stack of commands.
29 >>> from .engine import CommandMessage
31 Define two dummy commands for testing.
33 >>> class CommandA (object):
36 >>> class CommandB (CommandA):
40 Show off `CommandStack`\s functionality.
42 >>> c = CommandStack([CommandMessage(ca, {'param':'A'})])
43 >>> c.append(CommandMessage(cb, {'param':'B'}))
44 >>> c.append(CommandMessage(ca, {'param':'C'}))
45 >>> c.append(CommandMessage(cb, {'param':'D'}))
47 Implement a dummy :meth:`_execute` for testing.
49 >>> def execute(hooke, command_message):
50 ... cm = command_message
51 ... print 'EXECUTE', cm.command.name, cm.arguments
52 >>> c._execute = execute
54 >>> c.execute() # doctest: +ELLIPSIS
55 EXECUTE CommandA {'param': 'A'}
56 EXECUTE CommandB {'param': 'B'}
57 EXECUTE CommandA {'param': 'C'}
58 EXECUTE CommandB {'param': 'D'}
60 :meth:`filter` allows you to select which commands get executed.
61 If, for example, you are applying a set of commands to the current
62 :class:`~hooke.curve.Curve`, you may only want to execute
63 instances of :class:`~hooke.plugin.curve.CurveCommand`. Here we
64 only execute instances of `CommandB`.
66 >>> def filter(command_message):
67 ... return isinstance(command_message.command, CommandB)
70 Apply the stack to the current curve
71 >>> c.execute() # doctest: +ELLIPSIS
72 EXECUTE CommandB {'param': 'B'}
73 EXECUTE CommandB {'param': 'D'}
75 def execute(self, hooke):
76 """Execute a stack of commands.
82 for command_message in self:
83 if self.filter(command_message) == True:
84 self._execute(hooke, command_message)
86 def filter(self, command_message):
87 """Any commands in the stack that are not subclasses of
88 :class:`~hooke.plugin.curve.CurveCommand` are ignored.
92 def _execute(self, hooke, command_message):
93 hooke.run_command(command_message.command, command_message.arguments)