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 `engine` module provides :class:`CommandEngine` for executing
20 :class:`hooke.command.Command`\s.
25 from .command import NullQueue
28 class QueueMessage (object):
30 return self.__class__.__name__
33 class CloseEngine (QueueMessage):
37 class CommandMessage (QueueMessage):
38 """A message storing a command to run, `command` should be a
39 :class:`hooke.command.Command` instance, and `arguments` should be
40 a :class:`dict` with `argname` keys and `value` values to be
41 passed to the command.
43 def __init__(self, command, arguments=None):
44 self.command = command
47 self.arguments = arguments
50 class CommandEngine (object):
51 def run(self, hooke, ui_to_command_queue, command_to_ui_queue):
52 """Get a :class:`QueueMessage` from the incoming
53 `ui_to_command_queue` and act accordingly.
55 If the message is a :class:`CommandMessage` instance, the
56 command run may read subsequent input from
57 `ui_to_command_queue` (if it is an interactive command). The
58 command may also put assorted data into `command_to_ui_queue`.
60 When the command completes, it will put a
61 :class:`hooke.command.CommandExit` instance into
62 `command_to_ui_queue`, at which point the `CommandEngine` will
63 be ready to receive the next :class:`QueueMessage`.
65 log = logging.getLogger('hooke')
67 log.debug('engine waiting for command')
68 msg = ui_to_command_queue.get()
69 if isinstance(msg, CloseEngine):
70 command_to_ui_queue.put(hooke)
72 'engine closing, placed hooke instance in return queue')
74 assert isinstance(msg, CommandMessage), type(msg)
75 log.debug('engine running %s' % msg.command.name)
76 msg.command.run(hooke, ui_to_command_queue, command_to_ui_queue,
79 def run_command(self, hooke, command, arguments):
80 """Internal command execution.
82 This allows commands to execute sub commands and enables
83 :class:`~hooke.command_stack.CommandStack` execution.
85 Note that these commands *do not* have access to the usual UI
86 communication queues, so make sure they will not need user
89 command.run(hooke, NullQueue(), NullQueue(), arguments)