234b3f3d85dfbd0ed7f42584c1d04f51517cf6be
[hooke.git] / hooke / command_stack.py
1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
2 #
3 # This file is part of Hooke.
4 #
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.
9 #
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.
14 #
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/>.
18
19 """The ``command_stack`` module provides tools for managing and
20 executing stacks of :class:`~hooke.engine.CommandMessage`\s.
21 """
22
23 import os
24 import os.path
25
26 import yaml
27
28 from .engine import CommandMessage
29
30
31 class CommandStack (list):
32     """Store a stack of commands.
33
34     Examples
35     --------
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'}))
40
41     Implement a dummy :meth:`execute_command` for testing.
42     
43     >>> def execute_cmd(hooke, command_message, stack=None):
44     ...     cm = command_message
45     ...     print 'EXECUTE', cm.command, cm.arguments
46     >>> c.execute_command = execute_cmd
47
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'}
53
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`.
59     
60     >>> def filter(hooke, command_message):
61     ...     return command_message.command == 'CommandB'
62     >>> c.filter = filter
63
64     Apply the stack to the current curve.
65
66     >>> c.execute(hooke=None)  # doctest: +ELLIPSIS
67     EXECUTE CommandB {'param': 'B'}
68     EXECUTE CommandB {'param': 'D'}
69
70     Execute a new command and add it to the stack.
71
72     >>> cm = CommandMessage('CommandC', {'param':'E'})
73     >>> c.execute_command(hooke=None, command_message=cm)
74     EXECUTE CommandC {'param': 'E'}
75     >>> c.append(cm)
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}>']
82
83     The data-type is also pickleable, to ensure we can move it between
84     processes with :class:`multiprocessing.Queue`\s and easily save it
85     to disk.
86
87     >>> import pickle
88     >>> s = pickle.dumps(c)
89     >>> z = pickle.loads(s)
90     >>> print [repr(cm) for cm in c]  # doctest: +NORMALIZE_WHITESPACE
91     ['<CommandMessage CommandA {param: A}>',
92      '<CommandMessage CommandB {param: B}>',
93      '<CommandMessage CommandA {param: C}>',
94      '<CommandMessage CommandB {param: D}>',
95      '<CommandMessage CommandC {param: E}>']
96
97     There is also a convenience function for clearing the stack.
98
99     >>> c.clear()
100     >>> print [repr(cm) for cm in c]
101     []
102     """
103     def __getstate__(self):
104         state = [{'command':cm.command, 'arguments':cm.arguments}
105                 for cm in self]
106         return state
107
108     def __setstate__(self, state):
109         self.clear()
110         for cm_state in state:
111             self.append(CommandMessage(
112                     command=cm_state['command'],
113                     arguments=cm_state['arguments']))
114
115     def execute(self, hooke, stack=False):
116         """Execute a stack of commands.
117
118         See Also
119         --------
120         _execute, filter
121         """
122         for command_message in self:
123             if self.filter(hooke, command_message) == True:
124                 self.execute_command(
125                     hooke=hooke, command_message=command_message, stack=stack)
126
127     def filter(self, hooke, command_message):
128         """Return `True` to execute `command_message`, `False` otherwise.
129
130         The default implementation always returns `True`.
131         """
132         return True
133
134     def execute_command(self, hooke, command_message, stack=False):
135         arguments = dict(command_message.arguments)
136         arguments['stack'] = stack
137         hooke.run_command(command=command_message.command,
138                           arguments=arguments)
139
140     def clear(self):
141         while len(self) > 0:
142             self.pop()
143
144
145 class FileCommandStack (CommandStack):
146     """A file-backed :class:`CommandStack`.
147     """
148     version = '0.1'
149
150     def __init__(self, *args, **kwargs):
151         super(FileCommandStack, self).__init__(*args, **kwargs)
152         self.name = self.path = None
153
154     def __getstate__(self):
155         command_stack = super(FileCommandStack, self).__getstate__()
156         state = {
157             'command stack': command_stack,
158             'path': self.path,
159             'name': self.name,
160             }
161         return state
162
163     def __setstate__(self, state):
164         super(FileCommandStack, self).__setstate__(
165             state.get('command stack', []))
166         self.name = state.get('name', None)
167         self.path = None
168         self.set_path(state.get('path', None))
169
170     def set_path(self, path):
171         """Set the path (and possibly the name) of the command  stack.
172
173         Examples
174         --------
175         >>> c = FileCommandStack([CommandMessage('CommandA', {'param':'A'})])
176
177         :attr:`name` is set only if it starts out equal to `None`.
178         >>> c.name == None
179         True
180         >>> c.set_path(os.path.join('path', 'to', 'my', 'command', 'stack'))
181         >>> c.path
182         'path/to/my/command/stack'
183         >>> c.name
184         'stack'
185         >>> c.set_path(os.path.join('another', 'path'))
186         >>> c.path
187         'another/path'
188         >>> c.name
189         'stack'
190         """
191         if path != None:
192             self.path = path
193             if self.name == None:
194                 self.name = os.path.basename(path)
195
196     def save(self, path=None, makedirs=True):
197         """Saves the command stack to `path`.
198         """
199         self.set_path(path)
200         dirname = os.path.dirname(self.path) or '.'
201         if makedirs == True and not os.path.isdir(dirname):
202             os.makedirs(dirname)
203         with open(self.path, 'w') as f:
204             f.write(self.flatten())
205
206     def load(self, path=None):
207         """Load a command stack from `path`.
208         """
209         self.set_path(path)
210         with open(self.path, 'r') as f:
211             text = f.read()
212         self.from_string(text)
213
214     def flatten(self):
215         """Create a string representation of the command stack.
216
217         A playlist is a YAML document with the following syntax::
218
219             - arguments: {param: A}
220               command: CommandA
221             - arguments: {param: B, ...}
222               command: CommandB
223             ...
224
225         Examples
226         --------
227         >>> c = FileCommandStack([CommandMessage('CommandA', {'param':'A'})])
228         >>> c.append(CommandMessage('CommandB', {'param':'B'}))
229         >>> c.append(CommandMessage('CommandA', {'param':'C'}))
230         >>> c.append(CommandMessage('CommandB', {'param':'D'}))
231         >>> print c.flatten()
232         - arguments: {param: A}
233           command: CommandA
234         - arguments: {param: B}
235           command: CommandB
236         - arguments: {param: C}
237           command: CommandA
238         - arguments: {param: D}
239           command: CommandB
240         <BLANKLINE>
241         """
242         return yaml.dump([{'command':cm.command,'arguments':cm.arguments}
243                           for cm in self])
244
245     def from_string(self, string):
246         """Load a playlist from a string.
247
248         .. warning:: This is *not safe* with untrusted input.
249
250         Examples
251         --------
252
253         >>> string = '''- arguments: {param: A}
254         ...   command: CommandA
255         ... - arguments: {param: B}
256         ...   command: CommandB
257         ... - arguments: {param: C}
258         ...   command: CommandA
259         ... - arguments: {param: D}
260         ...   command: CommandB
261         ... '''
262         >>> c = FileCommandStack()
263         >>> c.from_string(string)
264         >>> print [repr(cm) for cm in c]  # doctest: +NORMALIZE_WHITESPACE
265         ['<CommandMessage CommandA {param: A}>',
266          '<CommandMessage CommandB {param: B}>',
267          '<CommandMessage CommandA {param: C}>',
268          '<CommandMessage CommandB {param: D}>']
269         """
270         for x in yaml.load(string):
271             self.append(CommandMessage(command=x['command'],
272                                        arguments=x['arguments']))