source: orange/Orange/OrangeCanvas/main.py @ 11167:74773cf295d6

Revision 11167:74773cf295d6, 6.9 KB checked in by Ales Erjavec <ales.erjavec@…>, 18 months ago (diff)

Added 'Output' window showing redirected stdout/stderr.

Line 
1"""
2Orange Canvas main entry point
3
4"""
5
6import os
7import sys
8import logging
9import optparse
10import cPickle
11from contextlib import nested
12
13import pkg_resources
14
15from PyQt4.QtGui import QFont, QColor
16from PyQt4.QtCore import QRect, QSettings
17
18from Orange import OrangeCanvas
19from Orange.OrangeCanvas.application.application import CanvasApplication
20from Orange.OrangeCanvas.application.canvasmain import CanvasMainWindow
21
22from Orange.OrangeCanvas.gui.splashscreen import SplashScreen, QPixmap
23from Orange.OrangeCanvas.config import open_config, cache_dir
24from Orange.OrangeCanvas import config
25from Orange.OrangeCanvas.utils.redirect import redirect_stdout, redirect_stderr
26
27from Orange.OrangeCanvas.registry import qt
28from Orange.OrangeCanvas.registry import WidgetRegistry, set_global_registry
29from Orange.OrangeCanvas.registry import cache
30
31log = logging.getLogger(__name__)
32
33
34def qt_logging_handle(msg_type, message):
35    print msg_type, message
36
37
38def main(argv=None):
39    if argv is None:
40        argv = sys.argv[1:]
41
42    usage = "usage: %prog [options] [scheme_file]"
43    parser = optparse.OptionParser(usage=usage)
44
45    parser.add_option("--no-discovery",
46                      action="store_true",
47                      help="Don't run widget discovery "
48                           "(use full cache instead)")
49
50    parser.add_option("--force-discovery",
51                      action="store_true",
52                      help="Force full widget discovery "
53                           "(invalidate cache)")
54    parser.add_option("--no-welcome",
55                      action="store_true",
56                      help="Don't show welcome dialog.")
57    parser.add_option("--no-splash",
58                      action="store_true",
59                      help="Don't show splash screen.")
60    parser.add_option("-l", "--log-level",
61                      help="Logging level (0, 1, 2, 3)",
62                      type="int", default=1)
63    parser.add_option("--no-redirect",
64                      action="store_true",
65                      help="Do not redirect stdout/err to canvas output view.")
66    parser.add_option("--style",
67                      help="QStyle to use",
68                      type="str", default=None)
69    parser.add_option("--stylesheet",
70                      help="Application level CSS style sheet to use",
71                      type="str", default="orange.qss")
72    parser.add_option("--qt",
73                      help="Additional arguments for QApplication",
74                      type="str", default=None)
75
76    (options, args) = parser.parse_args(argv)
77
78    open_config()
79
80    levels = [logging.CRITICAL,
81              logging.WARN,
82              logging.INFO,
83              logging.DEBUG]
84
85    logging.basicConfig(level=levels[options.log_level])
86
87    log.info("Starting 'Orange Canvas' application.")
88
89    qt_argv = ["orange-canvas"]
90
91    if options.style is not None:
92        qt_argv += ["-style", options.style]
93
94    if options.qt is not None:
95        qt_argv += options.qt.split()
96
97    config.init()
98    settings = QSettings()
99
100    log.debug("Starting CanvasApplicaiton with argv = %r.", qt_argv)
101    app = CanvasApplication(qt_argv)
102
103    stylesheet = options.stylesheet
104    stylesheet_string = None
105
106    if stylesheet != "none":
107        if os.path.isfile(stylesheet):
108            stylesheet_string = open(stylesheet, "rb").read()
109        else:
110            if not os.path.splitext(stylesheet)[1]:
111                # no extension
112                stylesheet = os.path.extsep.join([stylesheet, "qss"])
113
114            pkg_name = OrangeCanvas.__name__
115            resource = os.path.join("styles", stylesheet)
116            if pkg_resources.resource_exists(pkg_name, resource):
117                stylesheet_string = pkg_resources.resource_string(
118                                        pkg_name, resource)
119            else:
120                log.info("%r style sheet not found.", stylesheet)
121
122    if stylesheet_string is not None:
123        app.setStyleSheet(stylesheet_string)
124
125    canvas_window = CanvasMainWindow()
126    canvas_window.resize(1024, 650)
127
128    if not options.force_discovery:
129        reg_cache = cache.registry_cache()
130    else:
131        reg_cache = None
132
133    widget_discovery = qt.QtWidgetDiscovery(cached_descriptions=reg_cache)
134
135    widget_registry = qt.QtWidgetRegistry()
136
137    widget_discovery.found_category.connect(
138        widget_registry.register_category
139    )
140    widget_discovery.found_widget.connect(
141        widget_registry.register_widget
142    )
143
144    want_splash = \
145        settings.value("startup/show-splash-screen", True).toPyObject() and \
146        not options.no_splash
147
148    if want_splash:
149        pm = QPixmap(pkg_resources.resource_filename(
150                        __name__, "icons/orange-splash-screen.png")
151                     )
152        # Text rectangle in which to fit the message.
153        rect = QRect(88, 193, 200, 20)
154        splash_screen = SplashScreen(pixmap=pm, textRect=rect)
155        splash_screen.setFont(QFont("Helvetica", 12))
156        color = QColor("#FFD39F")
157
158        def show_message(message):
159            splash_screen.showMessage(message, color=color)
160
161        widget_discovery.discovery_start.connect(splash_screen.show)
162        widget_discovery.discovery_process.connect(show_message)
163        widget_discovery.discovery_finished.connect(splash_screen.hide)
164
165    log.info("Running widget discovery process.")
166
167    cache_filename = os.path.join(cache_dir(), "widget-registry.pck")
168    if options.no_discovery:
169        widget_registry = cPickle.load(open(cache_filename, "rb"))
170        widget_registry = qt.QtWidgetRegistry(widget_registry)
171    else:
172        widget_discovery.run()
173        # Store cached descriptions
174        cache.save_registry_cache(widget_discovery.cached_descriptions)
175        cPickle.dump(WidgetRegistry(widget_registry),
176                     open(cache_filename, "wb"))
177    set_global_registry(widget_registry)
178    canvas_window.set_widget_registry(widget_registry)
179    canvas_window.show()
180
181    want_welcome = \
182        settings.value("welcomedialog/show-at-startup", True).toBool() \
183        and not options.no_welcome
184
185    canvas_window.raise_()
186
187    if want_welcome and not args:
188        canvas_window.welcome_dialog()
189
190    elif args:
191        log.info("Loading a scheme from the command line argument %r",
192                 args[0])
193        canvas_window.load_scheme(args[0])
194
195    disable_redirect = \
196        settings.value("mainwindow/no-stdout-redirect", False).toBool() or \
197        options.no_redirect
198
199    if not disable_redirect:
200        output = canvas_window.output_view()
201    else:
202        output = None
203
204    with nested(redirect_stdout(output), redirect_stderr(output)):
205        log.info("Entering main event loop.")
206        try:
207            status = app.exec_()
208        except BaseException:
209            log.error("Error in main event loop.", exc_info=True)
210
211    canvas_window.deleteLater()
212    app.processEvents()
213    app.flush()
214    del canvas_window
215    del app
216    return status
217
218
219if __name__ == "__main__":
220    sys.exit(main())
Note: See TracBrowser for help on using the repository browser.