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
30 >>> c = CommandStack([CommandMessage('CommandA', {'param':'A'})])
31 >>> c.append(CommandMessage('CommandB', {'param':'B'}))
32 >>> c.append(CommandMessage('CommandA', {'param':'C'}))
33 >>> c.append(CommandMessage('CommandB', {'param':'D'}))
35 Implement a dummy :meth:`_execute` for testing.
37 >>> def execute(hooke, command_message):
38 ... cm = command_message
39 ... print 'EXECUTE', cm.command, cm.arguments
40 >>> c._execute = execute
42 >>> c.execute(hooke=None) # doctest: +ELLIPSIS
43 EXECUTE CommandA {'param': 'A'}
44 EXECUTE CommandB {'param': 'B'}
45 EXECUTE CommandA {'param': 'C'}
46 EXECUTE CommandB {'param': 'D'}
48 :meth:`filter` allows you to select which commands get executed.
49 If, for example, you are applying a set of commands to the current
50 :class:`~hooke.curve.Curve`, you may only want to execute
51 instances of :class:`~hooke.plugin.curve.CurveCommand`. Here we
52 only execute commands named `CommandB`.
54 >>> def filter(hooke, command_message):
55 ... return command_message.command == 'CommandB'
58 Apply the stack to the current curve
59 >>> c.execute(hooke=None) # doctest: +ELLIPSIS
60 EXECUTE CommandB {'param': 'B'}
61 EXECUTE CommandB {'param': 'D'}
63 def execute(self, hooke):
64 """Execute a stack of commands.
70 for command_message in self:
71 if self.filter(hooke, command_message) == True:
72 self._execute(hooke, command_message)
74 def filter(self, hooke, command_message):
75 """Return `True` to execute `command_message`, `False` otherwise.
77 The default implementation always returns `True`.
81 def _execute(self, hooke, command_message):
82 hooke.run_command(command_message.command, command_message.arguments)