Broke out Hooke.run and Hooke.run_lines into HookeRunner.
[hooke.git] / hooke / hooke.py
1 # Copyright (C) 2008-2010 Fabrizio Benedetti
2 #                         Massimo Sandal <devicerandom@gmail.com>
3 #                         Rolf Schmidt <rschmidt@alcor.concordia.ca>
4 #                         W. Trevor King <wking@drexel.edu>
5 #
6 # This file is part of Hooke.
7 #
8 # Hooke is free software: you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation, either
11 # version 3 of the License, or (at your option) any later version.
12 #
13 # Hooke is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU Lesser General Public License for more details.
17 #
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with Hooke.  If not, see
20 # <http://www.gnu.org/licenses/>.
21
22 """Hooke - A force spectroscopy review & analysis tool.
23 """
24
25 import multiprocessing
26 import optparse
27 import os.path
28 import unittest
29 import sys
30
31 from . import engine as engine
32 from . import config as config_mod
33 from . import playlist as playlist
34 from . import plugin as plugin_mod
35 from . import driver as driver_mod
36 from . import ui as ui
37
38
39 class Hooke (object):
40     def __init__(self, config=None, debug=0):
41         self.debug = debug
42         default_settings = (config_mod.DEFAULT_SETTINGS
43                             + plugin_mod.default_settings()
44                             + driver_mod.default_settings()
45                             + ui.default_settings())
46         if config == None:
47             config = config_mod.HookeConfigParser(
48                 paths=config_mod.DEFAULT_PATHS,
49                 default_settings=default_settings)
50             config.read()
51         self.config = config
52         self.load_plugins()
53         self.load_drivers()
54         self.load_ui()
55         self.command = engine.CommandEngine()
56
57         self.playlists = playlist.NoteIndexList()
58
59     def load_plugins(self):
60         self.plugins = plugin_mod.load_graph(
61             plugin_mod.PLUGIN_GRAPH, self.config, include_section='plugins')
62         self.commands = []
63         for plugin in self.plugins:
64             self.commands.extend(plugin.commands())
65
66     def load_drivers(self):
67         self.drivers = plugin_mod.load_graph(
68             driver_mod.DRIVER_GRAPH, self.config, include_section='drivers')
69
70     def load_ui(self):
71         self.ui = ui.load_ui(self.config)
72
73     def close(self):
74         self.config.write() # Does not preserve original comments
75
76 class HookeRunner (object):
77     def run(self, hooke):
78         """Run Hooke's main execution loop.
79
80         Spawns a :class:`hooke.engine.CommandEngine` subprocess and
81         then runs the UI, rejoining the `CommandEngine` process after
82         the UI exits.
83         """
84         ui_to_command,command_to_ui,command = self._setup_run(hooke)
85         try:
86             self.ui.run(hooke.commands, ui_to_command, command_to_ui)
87         finally:
88             hooke = self._cleanup_run(ui_to_command, command_to_ui, command)
89         return hooke
90
91     def run_lines(self, hooke, lines):
92         """Run the pre-set commands `lines` with the "command line" UI.
93
94         Allows for non-interactive sessions that are otherwise
95         equivalent to :meth:'.run'.
96         """
97         cmdline = ui.load_ui(hooke.config, 'command line')
98         ui_to_command,command_to_ui,command = self._setup_run(hooke)
99         try:
100             cmdline.run_lines(
101                 hooke.commands, ui_to_command, command_to_ui, lines)
102         finally:
103             hooke = self._cleanup_run(ui_to_command, command_to_ui, command)
104         return hooke
105
106     def _setup_run(self, hooke):
107         ui_to_command = multiprocessing.Queue()
108         command_to_ui = multiprocessing.Queue()
109         manager = multiprocessing.Manager()        
110         command = multiprocessing.Process(name='command engine',
111             target=hooke.command.run, args=(hooke, ui_to_command, command_to_ui))
112         command.start()
113         return (ui_to_command, command_to_ui, command)
114
115     def _cleanup_run(self, ui_to_command, command_to_ui, command):
116         ui_to_command.put(ui.CloseEngine())
117         hooke = command_to_ui.get()
118         assert isinstance(hooke, Hooke)
119         command.join()
120         return hooke
121
122
123 def main():
124     p = optparse.OptionParser()
125     p.add_option(
126         '-s', '--script', dest='script', metavar='FILE',
127         help='Script of command line Hooke commands to run.')
128     p.add_option(
129         '-c', '--command', dest='commands', metavar='COMMAND',
130         action='append', default=[],
131         help='Add a command line Hooke command to run.')
132     options,arguments = p.parse_args()
133     if len(arguments) > 0:
134         print >> sys.stderr, 'Too many arguments to %s: %d > 0' \
135             % (sys.argv[0], len(arguments))
136         print >> sys.stderr, p.help()
137         sys.exit(1)
138
139     hooke = Hooke(debug=__debug__)
140     runner = HookeRunner()
141
142     if options.script != None:
143         f = open(os.path.expanduser(options.script), 'r')
144         options.commands.extend(f.readlines())
145         f.close
146     if len(options.commands) > 0:
147         try:
148             hooke = runner.run_lines(hooke, options.commands)
149         finally:
150             hooke.close()
151         sys.exit(0)
152
153     try:
154         hooke = runner.run(hooke)
155     finally:
156         hooke.close()
157
158 if __name__ == '__main__':
159     main()