Transition from v0.1 XML playlists to v0.2 YAML playlists.
[hooke.git] / hooke / engine.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 `engine` module provides :class:`CommandEngine` for executing
20 :class:`hooke.command.Command`\s.
21 """
22
23 import logging
24 from Queue import Queue, Empty
25
26 from .command import NullQueue
27
28
29 class QueueMessage (object):
30     def __str__(self):
31         return self.__class__.__name__
32
33
34 class CloseEngine (QueueMessage):
35     pass
36
37
38 class CommandMessage (QueueMessage):
39     """A message storing a command to run, `command` should be the
40     name of a :class:`hooke.command.Command` instance, and `arguments`
41     should be a :class:`dict` with `argname` keys and `value` values
42     to be passed to the command.
43     """
44     def __init__(self, command, arguments=None):
45         self.command = command
46         if arguments == None:
47             arguments = {}
48         self.arguments = arguments
49
50     def __str__(self):
51         return str(self.__unicode__())
52
53     def __unicode__(self):
54         """Return a unicode representation of the `CommandMessage`.
55
56         Examples
57         --------
58         >>> from .compat.odict import odict
59         >>> cm = CommandMessage('command A')
60         >>> print unicode(cm)
61         <CommandMessage command A>
62         >>> cm.arguments = odict([('param a','value a'), ('param b', 'value b')])
63         >>> print unicode(cm)
64         <CommandMessage command A {param a: value a, param b: value b}>
65
66         The parameters are sorted by name, so you won't be surprised
67         in any doctests, etc.
68
69         >>> cm.arguments = odict([('param b','value b'), ('param a', 'value a')])
70         >>> print unicode(cm)
71         <CommandMessage command A {param a: value a, param b: value b}>
72         """
73         if len(self.arguments) > 0:
74             return u'<%s %s {%s}>' % (
75                 self.__class__.__name__, self.command,
76                 ', '.join(['%s: %s' % (key, value)
77                            for key,value in sorted(self.arguments.items())]))
78         return u'<%s %s>' % (self.__class__.__name__, self.command)
79
80     def __repr__(self):
81         return self.__str__()
82
83
84 class CommandEngine (object):
85     def run(self, hooke, ui_to_command_queue, command_to_ui_queue):
86         """Get a :class:`QueueMessage` from the incoming
87         `ui_to_command_queue` and act accordingly.
88
89         If the message is a :class:`CommandMessage` instance, the
90         command run may read subsequent input from
91         `ui_to_command_queue` (if it is an interactive command).  The
92         command may also put assorted data into `command_to_ui_queue`.
93
94         When the command completes, it will put a
95         :class:`hooke.command.CommandExit` instance into
96         `command_to_ui_queue`, at which point the `CommandEngine` will
97         be ready to receive the next :class:`QueueMessage`.
98         """
99         log = logging.getLogger('hooke')
100         log.debug('engine starting')
101         while True:
102             log.debug('engine waiting for command')
103             msg = ui_to_command_queue.get()
104             if isinstance(msg, CloseEngine):
105                 command_to_ui_queue.put(hooke)
106                 log.debug(
107                     'engine closing, placed hooke instance in return queue')
108                 break
109             assert isinstance(msg, CommandMessage), type(msg)
110             log.debug('engine running %s' % msg)
111             cmd = hooke.command_by_name[msg.command]
112             cmd.run(hooke, ui_to_command_queue, command_to_ui_queue,
113                     **msg.arguments)
114
115     def run_command(self, hooke, command, arguments):
116         """Run the command named `command` with `arguments` using
117         :meth:`~hooke.engine.CommandEngine.run_command`.
118
119         This allows commands to execute sub commands and enables
120         :class:`~hooke.command_stack.CommandStack` execution.
121
122         Note that these commands *do not* have access to the usual UI
123         communication queues, so make sure they will not need user
124         interaction.
125         """
126         log = logging.getLogger('hooke')
127         log.debug('engine running internal %s'
128                   % CommandMessage(command, arguments))
129         outqueue = Queue()
130         cmd = hooke.command_by_name[command]
131         cmd.run(hooke, NullQueue(), outqueue, **arguments)
132         while True:
133             try:
134                 msg = outqueue.get(block=False)
135             except Empty:
136                 break
137             log.debug('engine message from %s (%s): %s' % (command, type(msg), msg))