source: orange/Orange/OrangeCanvas/main.py @ 11168:66793f8e1739

Revision 11168:66793f8e1739, 6.9 KB checked in by Ales Erjavec <ales.erjavec@…>, 18 months ago (diff)

Fixed Qt's plugin search path on Windows.

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    levels = [logging.CRITICAL,
79              logging.WARN,
80              logging.INFO,
81              logging.DEBUG]
82
83    logging.basicConfig(level=levels[options.log_level])
84
85    log.info("Starting 'Orange Canvas' application.")
86
87    qt_argv = ["orange-canvas"]
88
89    if options.style is not None:
90        qt_argv += ["-style", options.style]
91
92    if options.qt is not None:
93        qt_argv += options.qt.split()
94
95    log.debug("Starting CanvasApplicaiton with argv = %r.", qt_argv)
96    app = CanvasApplication(qt_argv)
97
98    # Note: config.init must be called after the QApplication constructor
99    config.init()
100    settings = QSettings()
101
102    stylesheet = options.stylesheet
103    stylesheet_string = None
104
105    if stylesheet != "none":
106        if os.path.isfile(stylesheet):
107            stylesheet_string = open(stylesheet, "rb").read()
108        else:
109            if not os.path.splitext(stylesheet)[1]:
110                # no extension
111                stylesheet = os.path.extsep.join([stylesheet, "qss"])
112
113            pkg_name = OrangeCanvas.__name__
114            resource = os.path.join("styles", stylesheet)
115            if pkg_resources.resource_exists(pkg_name, resource):
116                stylesheet_string = pkg_resources.resource_string(
117                                        pkg_name, resource)
118            else:
119                log.info("%r style sheet not found.", stylesheet)
120
121    if stylesheet_string is not None:
122        app.setStyleSheet(stylesheet_string)
123
124    canvas_window = CanvasMainWindow()
125    canvas_window.resize(1024, 650)
126
127    if not options.force_discovery:
128        reg_cache = cache.registry_cache()
129    else:
130        reg_cache = None
131
132    widget_discovery = qt.QtWidgetDiscovery(cached_descriptions=reg_cache)
133
134    widget_registry = qt.QtWidgetRegistry()
135
136    widget_discovery.found_category.connect(
137        widget_registry.register_category
138    )
139    widget_discovery.found_widget.connect(
140        widget_registry.register_widget
141    )
142
143    want_splash = \
144        settings.value("startup/show-splash-screen", True).toPyObject() and \
145        not options.no_splash
146
147    if want_splash:
148        pm = QPixmap(pkg_resources.resource_filename(
149                        __name__, "icons/orange-splash-screen.png")
150                     )
151        # Text rectangle in which to fit the message.
152        rect = QRect(88, 193, 200, 20)
153        splash_screen = SplashScreen(pixmap=pm, textRect=rect)
154        splash_screen.setFont(QFont("Helvetica", 12))
155        color = QColor("#FFD39F")
156
157        def show_message(message):
158            splash_screen.showMessage(message, color=color)
159
160        widget_discovery.discovery_start.connect(splash_screen.show)
161        widget_discovery.discovery_process.connect(show_message)
162        widget_discovery.discovery_finished.connect(splash_screen.hide)
163
164    log.info("Running widget discovery process.")
165
166    cache_filename = os.path.join(cache_dir(), "widget-registry.pck")
167    if options.no_discovery:
168        widget_registry = cPickle.load(open(cache_filename, "rb"))
169        widget_registry = qt.QtWidgetRegistry(widget_registry)
170    else:
171        widget_discovery.run()
172        # Store cached descriptions
173        cache.save_registry_cache(widget_discovery.cached_descriptions)
174        cPickle.dump(WidgetRegistry(widget_registry),
175                     open(cache_filename, "wb"))
176    set_global_registry(widget_registry)
177    canvas_window.set_widget_registry(widget_registry)
178    canvas_window.show()
179
180    want_welcome = \
181        settings.value("welcomedialog/show-at-startup", True).toBool() \
182        and not options.no_welcome
183
184    canvas_window.raise_()
185
186    if want_welcome and not args:
187        canvas_window.welcome_dialog()
188
189    elif args:
190        log.info("Loading a scheme from the command line argument %r",
191                 args[0])
192        canvas_window.load_scheme(args[0])
193
194    disable_redirect = \
195        settings.value("mainwindow/no-stdout-redirect", False).toBool() or \
196        options.no_redirect
197
198    if not disable_redirect:
199        output = canvas_window.output_view()
200    else:
201        output = None
202
203    with nested(redirect_stdout(output), redirect_stderr(output)):
204        log.info("Entering main event loop.")
205        try:
206            status = app.exec_()
207        except BaseException:
208            log.error("Error in main event loop.", exc_info=True)
209
210    canvas_window.deleteLater()
211    app.processEvents()
212    app.flush()
213    del canvas_window
214    del app
215    return status
216
217
218if __name__ == "__main__":
219    sys.exit(main())
Note: See TracBrowser for help on using the repository browser.