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.
28 from .engine import CommandMessage
31 class CommandStack (list):
32 """Store a stack of commands.
36 >>> c = CommandStack([CommandMessage('CommandA', {'param':'A'})])
37 >>> c.append(CommandMessage('CommandB', {'param':'B'}))
38 >>> c.append(CommandMessage('CommandA', {'param':'C'}))
39 >>> c.append(CommandMessage('CommandB', {'param':'D'}))
41 Implement a dummy :meth:`execute_command` for testing.
43 >>> def execute_cmd(hooke, command_message):
44 ... cm = command_message
45 ... print 'EXECUTE', cm.command, cm.arguments
46 >>> c.execute_command = execute_cmd
48 >>> c.execute(hooke=None) # doctest: +ELLIPSIS
49 EXECUTE CommandA {'param': 'A'}
50 EXECUTE CommandB {'param': 'B'}
51 EXECUTE CommandA {'param': 'C'}
52 EXECUTE CommandB {'param': 'D'}
54 :meth:`filter` allows you to select which commands get executed.
55 If, for example, you are applying a set of commands to the current
56 :class:`~hooke.curve.Curve`, you may only want to execute
57 instances of :class:`~hooke.plugin.curve.CurveCommand`. Here we
58 only execute commands named `CommandB`.
60 >>> def filter(hooke, command_message):
61 ... return command_message.command == 'CommandB'
64 Apply the stack to the current curve.
66 >>> c.execute(hooke=None) # doctest: +ELLIPSIS
67 EXECUTE CommandB {'param': 'B'}
68 EXECUTE CommandB {'param': 'D'}
70 Execute a new command and add it to the stack.
72 >>> cm = CommandMessage('CommandC', {'param':'E'})
73 >>> c.execute_command(hooke=None, command_message=cm)
74 EXECUTE CommandC {'param': 'E'}
76 >>> print [repr(cm) for cm in c] # doctest: +NORMALIZE_WHITESPACE
77 ['<CommandMessage CommandA {param: A}>',
78 '<CommandMessage CommandB {param: B}>',
79 '<CommandMessage CommandA {param: C}>',
80 '<CommandMessage CommandB {param: D}>',
81 '<CommandMessage CommandC {param: E}>']
83 There is also a convenience function for clearing the stack.
86 >>> print [repr(cm) for cm in c]
89 def execute(self, hooke):
90 """Execute a stack of commands.
96 for command_message in self:
97 if self.filter(hooke, command_message) == True:
99 hooke=hooke, command_message=command_message)
101 def filter(self, hooke, command_message):
102 """Return `True` to execute `command_message`, `False` otherwise.
104 The default implementation always returns `True`.
108 def execute_command(self, hooke, command_message):
109 hooke.run_command(command=command_message.command,
110 arguments=command_message.arguments)
117 class FileCommandStack (CommandStack):
118 """A file-backed :class:`CommandStack`.
122 def __init__(self, *args, **kwargs):
123 super(FileCommandStack, self).__init__(*args, **kwargs)
127 def set_path(self, path):
128 """Set the path (and possibly the name) of the command stack.
132 >>> c = FileCommandStack([CommandMessage('CommandA', {'param':'A'})])
134 :attr:`name` is set only if it starts out equal to `None`.
137 >>> c.set_path(os.path.join('path', 'to', 'my', 'command', 'stack'))
139 'path/to/my/command/stack'
142 >>> c.set_path(os.path.join('another', 'path'))
150 if self.name == None:
151 self.name = os.path.basename(path)
153 def save(self, path=None, makedirs=True):
154 """Saves the command stack to `path`.
157 dirname = os.path.dirname(self.path)
158 if makedirs == True and not os.path.isdir(dirname):
160 with open(self.path, 'w') as f:
161 f.write(self.flatten())
163 def load(self, path=None):
164 """Load a command stack from `path`.
167 with open(self.path, 'r') as f:
169 self.from_string(text)
172 """Create a string representation of the command stack.
174 A playlist is a YAML document with the following syntax::
176 - arguments: {param: A}
178 - arguments: {param: B, ...}
184 >>> c = FileCommandStack([CommandMessage('CommandA', {'param':'A'})])
185 >>> c.append(CommandMessage('CommandB', {'param':'B'}))
186 >>> c.append(CommandMessage('CommandA', {'param':'C'}))
187 >>> c.append(CommandMessage('CommandB', {'param':'D'}))
188 >>> print c.flatten()
189 - arguments: {param: A}
191 - arguments: {param: B}
193 - arguments: {param: C}
195 - arguments: {param: D}
199 return yaml.dump([{'command':cm.command,'arguments':cm.arguments}
202 def from_string(self, string):
203 """Load a playlist from a string.
205 .. warning:: This is *not safe* with untrusted input.
210 >>> string = '''- arguments: {param: A}
211 ... command: CommandA
212 ... - arguments: {param: B}
213 ... command: CommandB
214 ... - arguments: {param: C}
215 ... command: CommandA
216 ... - arguments: {param: D}
217 ... command: CommandB
219 >>> c = FileCommandStack()
220 >>> c.from_string(string)
221 >>> print [repr(cm) for cm in c] # doctest: +NORMALIZE_WHITESPACE
222 ['<CommandMessage CommandA {param: A}>',
223 '<CommandMessage CommandB {param: B}>',
224 '<CommandMessage CommandA {param: C}>',
225 '<CommandMessage CommandB {param: D}>']
227 for x in yaml.load(string):
228 self.append(CommandMessage(command=x['command'],
229 arguments=x['arguments']))