17a633ba954343996c6ef97be56ea3da6a12ac64
[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):
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     There is also a convenience function for clearing the stack.
84
85     >>> c.clear()
86     >>> print [repr(cm) for cm in c]
87     []
88     """
89     def execute(self, hooke, stack=False):
90         """Execute a stack of commands.
91
92         See Also
93         --------
94         _execute, filter
95         """
96         for command_message in self:
97             if self.filter(hooke, command_message) == True:
98                 self.execute_command(
99                     hooke=hooke, command_message=command_message, stack=stack)
100
101     def filter(self, hooke, command_message):
102         """Return `True` to execute `command_message`, `False` otherwise.
103
104         The default implementation always returns `True`.
105         """
106         return True
107
108     def execute_command(self, hooke, command_message, stack=False):
109         arguments = dict(command_message.arguments)
110         arguments['stack'] = stack
111         hooke.run_command(command=command_message.command,
112                           arguments=arguments)
113
114     def clear(self):
115         while len(self) > 0:
116             self.pop()
117
118
119 class FileCommandStack (CommandStack):
120     """A file-backed :class:`CommandStack`.
121     """
122     version = '0.1'
123
124     def __init__(self, *args, **kwargs):
125         super(FileCommandStack, self).__init__(*args, **kwargs)
126         self.name = None
127         self.path = None
128
129     def set_path(self, path):
130         """Set the path (and possibly the name) of the command  stack.
131
132         Examples
133         --------
134         >>> c = FileCommandStack([CommandMessage('CommandA', {'param':'A'})])
135
136         :attr:`name` is set only if it starts out equal to `None`.
137         >>> c.name == None
138         True
139         >>> c.set_path(os.path.join('path', 'to', 'my', 'command', 'stack'))
140         >>> c.path
141         'path/to/my/command/stack'
142         >>> c.name
143         'stack'
144         >>> c.set_path(os.path.join('another', 'path'))
145         >>> c.path
146         'another/path'
147         >>> c.name
148         'stack'
149         """
150         if path != None:
151             self.path = path
152             if self.name == None:
153                 self.name = os.path.basename(path)
154
155     def save(self, path=None, makedirs=True):
156         """Saves the command stack to `path`.
157         """
158         self.set_path(path)
159         dirname = os.path.dirname(self.path) or '.'
160         if makedirs == True and not os.path.isdir(dirname):
161             os.makedirs(dirname)
162         with open(self.path, 'w') as f:
163             f.write(self.flatten())
164
165     def load(self, path=None):
166         """Load a command stack from `path`.
167         """
168         self.set_path(path)
169         with open(self.path, 'r') as f:
170             text = f.read()
171         self.from_string(text)
172
173     def flatten(self):
174         """Create a string representation of the command stack.
175
176         A playlist is a YAML document with the following syntax::
177
178             - arguments: {param: A}
179               command: CommandA
180             - arguments: {param: B, ...}
181               command: CommandB
182             ...
183
184         Examples
185         --------
186         >>> c = FileCommandStack([CommandMessage('CommandA', {'param':'A'})])
187         >>> c.append(CommandMessage('CommandB', {'param':'B'}))
188         >>> c.append(CommandMessage('CommandA', {'param':'C'}))
189         >>> c.append(CommandMessage('CommandB', {'param':'D'}))
190         >>> print c.flatten()
191         - arguments: {param: A}
192           command: CommandA
193         - arguments: {param: B}
194           command: CommandB
195         - arguments: {param: C}
196           command: CommandA
197         - arguments: {param: D}
198           command: CommandB
199         <BLANKLINE>
200         """
201         return yaml.dump([{'command':cm.command,'arguments':cm.arguments}
202                           for cm in self])
203
204     def from_string(self, string):
205         """Load a playlist from a string.
206
207         .. warning:: This is *not safe* with untrusted input.
208
209         Examples
210         --------
211
212         >>> string = '''- arguments: {param: A}
213         ...   command: CommandA
214         ... - arguments: {param: B}
215         ...   command: CommandB
216         ... - arguments: {param: C}
217         ...   command: CommandA
218         ... - arguments: {param: D}
219         ...   command: CommandB
220         ... '''
221         >>> c = FileCommandStack()
222         >>> c.from_string(string)
223         >>> print [repr(cm) for cm in c]  # doctest: +NORMALIZE_WHITESPACE
224         ['<CommandMessage CommandA {param: A}>',
225          '<CommandMessage CommandB {param: B}>',
226          '<CommandMessage CommandA {param: C}>',
227          '<CommandMessage CommandB {param: D}>']
228         """
229         for x in yaml.load(string):
230             self.append(CommandMessage(command=x['command'],
231                                        arguments=x['arguments']))