202e599a7ffafcaf703dd48768016c04401c7cf6
[hooke.git] / hooke / command_stack.py
1 # Copyright (C) 2010-2011 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
63     Apply the stack to the current curve.
64
65     >>> c.execute(hooke=None, filter=filter)  # doctest: +ELLIPSIS
66     EXECUTE CommandB {'param': 'B'}
67     EXECUTE CommandB {'param': 'D'}
68
69     Execute a new command and add it to the stack.
70
71     >>> cm = CommandMessage('CommandC', {'param':'E'})
72     >>> c.execute_command(hooke=None, command_message=cm)
73     EXECUTE CommandC {'param': 'E'}
74     >>> c.append(cm)
75     >>> print [repr(cm) for cm in c]  # doctest: +NORMALIZE_WHITESPACE
76     ['<CommandMessage CommandA {param: A}>',
77      '<CommandMessage CommandB {param: B}>',
78      '<CommandMessage CommandA {param: C}>',
79      '<CommandMessage CommandB {param: D}>',
80      '<CommandMessage CommandC {param: E}>']
81
82     The data-type is also pickleable, which ensures we can move it
83     between processes with :class:`multiprocessing.Queue`\s and easily
84     save it to disk.  We must remove the unpickleable dummy executor
85     before testing though.
86
87     >>> c.execute_command  # doctest: +ELLIPSIS
88     <function execute_cmd at 0x...>
89     >>> del(c.__dict__['execute_command'])
90     >>> c.execute_command  # doctest: +ELLIPSIS
91     <bound method CommandStack.execute_command of ...>
92     
93     Lets also attach a child command message to demonstrate recursive
94     serialization (we can't append `c` itself because of
95     `Python issue 1062277`_).
96
97     .. _Python issue 1062277: http://bugs.python.org/issue1062277
98
99     >>> import copy
100     >>> c.append(CommandMessage('CommandD', {'param': copy.deepcopy(c)}))
101
102     Run the pickle (and YAML) tests.
103
104     >>> import pickle
105     >>> s = pickle.dumps(c)
106     >>> z = pickle.loads(s)
107     >>> print '\\n'.join([repr(cm) for cm in c]
108     ...     )  # doctest: +NORMALIZE_WHITESPACE,
109     <CommandMessage CommandA {param: A}>
110     <CommandMessage CommandB {param: B}>
111     <CommandMessage CommandA {param: C}>
112     <CommandMessage CommandB {param: D}>
113     <CommandMessage CommandC {param: E}>
114     <CommandMessage CommandD {param:
115       [<CommandMessage CommandA {param: A}>,
116        <CommandMessage CommandB {param: B}>,
117        <CommandMessage CommandA {param: C}>,
118        <CommandMessage CommandB {param: D}>,
119        <CommandMessage CommandC {param: E}>]}>
120     >>> import yaml
121     >>> print yaml.dump(c)  # doctest: +REPORT_UDIFF
122     !!python/object/new:hooke.command_stack.CommandStack
123     listitems:
124     - !!python/object:hooke.engine.CommandMessage
125       arguments: {param: A}
126       command: CommandA
127       explicit_user_call: true
128     - !!python/object:hooke.engine.CommandMessage
129       arguments: {param: B}
130       command: CommandB
131       explicit_user_call: true
132     - !!python/object:hooke.engine.CommandMessage
133       arguments: {param: C}
134       command: CommandA
135       explicit_user_call: true
136     - !!python/object:hooke.engine.CommandMessage
137       arguments: {param: D}
138       command: CommandB
139       explicit_user_call: true
140     - !!python/object:hooke.engine.CommandMessage
141       arguments: {param: E}
142       command: CommandC
143       explicit_user_call: true
144     - !!python/object:hooke.engine.CommandMessage
145       arguments:
146         param: !!python/object/new:hooke.command_stack.CommandStack
147           listitems:
148           - !!python/object:hooke.engine.CommandMessage
149             arguments: {param: A}
150             command: CommandA
151             explicit_user_call: true
152           - !!python/object:hooke.engine.CommandMessage
153             arguments: {param: B}
154             command: CommandB
155             explicit_user_call: true
156           - !!python/object:hooke.engine.CommandMessage
157             arguments: {param: C}
158             command: CommandA
159             explicit_user_call: true
160           - !!python/object:hooke.engine.CommandMessage
161             arguments: {param: D}
162             command: CommandB
163             explicit_user_call: true
164           - !!python/object:hooke.engine.CommandMessage
165             arguments: {param: E}
166             command: CommandC
167             explicit_user_call: true
168       command: CommandD
169       explicit_user_call: true
170     <BLANKLINE>
171
172     There is also a convenience function for clearing the stack.
173
174     >>> c.clear()
175     >>> print [repr(cm) for cm in c]
176     []
177
178     YAMLize a curve argument.
179
180     >>> from .curve import Curve
181     >>> c.append(CommandMessage('curve info', {'curve': Curve(path=None)}))
182     >>> print yaml.dump(c)  # doctest: +REPORT_UDIFF
183     !!python/object/new:hooke.command_stack.CommandStack
184     listitems:
185     - !!python/object:hooke.engine.CommandMessage
186       arguments:
187         curve: !!python/object:hooke.curve.Curve {}
188       command: curve info
189       explicit_user_call: true
190     <BLANKLINE>
191     """
192     def execute(self, hooke, filter=None, stack=False):
193         """Execute a stack of commands.
194
195         See Also
196         --------
197         execute_command, filter
198         """
199         if filter == None:
200             filter = self.filter
201         for command_message in self:
202             if filter(hooke, command_message) == True:
203                 self.execute_command(
204                     hooke=hooke, command_message=command_message, stack=stack)
205
206     def filter(self, hooke, command_message):
207         """Return `True` to execute `command_message`, `False` otherwise.
208
209         The default implementation always returns `True`.
210         """
211         return True
212
213     def execute_command(self, hooke, command_message, stack=False):
214         arguments = dict(command_message.arguments)
215         arguments['stack'] = stack
216         hooke.run_command(command=command_message.command,
217                           arguments=arguments)
218
219     def clear(self):
220         while len(self) > 0:
221             self.pop()
222
223
224 class FileCommandStack (CommandStack):
225     """A file-backed :class:`CommandStack`.
226     """
227     version = '0.1'
228
229     def __init__(self, *args, **kwargs):
230         super(FileCommandStack, self).__init__(*args, **kwargs)
231         self.name = self.path = None
232
233     def __setstate__(self, state):
234         self.name = self.path = None
235         for key,value in state.items():
236             setattr(self, key, value)
237         self.set_path(state.get('path', None))
238
239     def set_path(self, path):
240         """Set the path (and possibly the name) of the command  stack.
241
242         Examples
243         --------
244         >>> c = FileCommandStack([CommandMessage('CommandA', {'param':'A'})])
245
246         :attr:`name` is set only if it starts out equal to `None`.
247         >>> c.name == None
248         True
249         >>> c.set_path(os.path.join('path', 'to', 'my', 'command', 'stack'))
250         >>> c.path
251         'path/to/my/command/stack'
252         >>> c.name
253         'stack'
254         >>> c.set_path(os.path.join('another', 'path'))
255         >>> c.path
256         'another/path'
257         >>> c.name
258         'stack'
259         """
260         if path != None:
261             self.path = path
262             if self.name == None:
263                 self.name = os.path.basename(path)
264
265     def save(self, path=None, makedirs=True):
266         """Saves the command stack to `path`.
267         """
268         self.set_path(path)
269         dirname = os.path.dirname(self.path) or '.'
270         if makedirs == True and not os.path.isdir(dirname):
271             os.makedirs(dirname)
272         with open(self.path, 'w') as f:
273             f.write(self.flatten())
274
275     def load(self, path=None):
276         """Load a command stack from `path`.
277         """
278         self.set_path(path)
279         with open(self.path, 'r') as f:
280             text = f.read()
281         self.from_string(text)
282
283     def flatten(self):
284         """Create a string representation of the command stack.
285
286         A playlist is a YAML document with the following syntax::
287
288             - arguments: {param: A}
289               command: CommandA
290             - arguments: {param: B, ...}
291               command: CommandB
292             ...
293
294         Examples
295         --------
296         >>> c = FileCommandStack([CommandMessage('CommandA', {'param':'A'})])
297         >>> c.append(CommandMessage('CommandB', {'param':'B'}))
298         >>> c.append(CommandMessage('CommandA', {'param':'C'}))
299         >>> c.append(CommandMessage('CommandB', {'param':'D'}))
300         >>> print c.flatten()
301         - arguments: {param: A}
302           command: CommandA
303         - arguments: {param: B}
304           command: CommandB
305         - arguments: {param: C}
306           command: CommandA
307         - arguments: {param: D}
308           command: CommandB
309         <BLANKLINE>
310         """
311         return yaml.dump([{'command':cm.command,'arguments':cm.arguments}
312                           for cm in self])
313
314     def from_string(self, string):
315         """Load a playlist from a string.
316
317         .. warning:: This is *not safe* with untrusted input.
318
319         Examples
320         --------
321
322         >>> string = '''- arguments: {param: A}
323         ...   command: CommandA
324         ... - arguments: {param: B}
325         ...   command: CommandB
326         ... - arguments: {param: C}
327         ...   command: CommandA
328         ... - arguments: {param: D}
329         ...   command: CommandB
330         ... '''
331         >>> c = FileCommandStack()
332         >>> c.from_string(string)
333         >>> print [repr(cm) for cm in c]  # doctest: +NORMALIZE_WHITESPACE
334         ['<CommandMessage CommandA {param: A}>',
335          '<CommandMessage CommandB {param: B}>',
336          '<CommandMessage CommandA {param: C}>',
337          '<CommandMessage CommandB {param: D}>']
338         """
339         for x in yaml.load(string):
340             self.append(CommandMessage(command=x['command'],
341                                        arguments=x['arguments']))