source: sasview/src/sas/sasview/sasview.py @ 1693141

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalcmagnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 1693141 was 1693141, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

fix broken startup

  • Property mode set to 100644
File size: 8.1 KB
Line 
1# -*- coding: utf-8 -*-
2"""
3Base module for loading and running the main SasView application.
4"""
5################################################################################
6# This software was developed by the University of Tennessee as part of the
7# Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
8# project funded by the US National Science Foundation.
9#
10# See the license text in license.txt
11#
12# copyright 2009, University of Tennessee
13################################################################################
14import os
15import os.path
16import sys
17import traceback
18import logging
19
20reload(sys)
21sys.setdefaultencoding("iso-8859-1")
22
23APP_NAME = 'SasView'
24PLUGIN_MODEL_DIR = 'plugin_models'
25
26class SasView(object):
27    """
28    Main class for running the SasView application
29    """
30    def __init__(self):
31        """
32        """
33        logger = logging.getLogger(__name__)
34
35        from sas.sasgui.guiframe.gui_manager import SasViewApp
36        self.gui = SasViewApp(0)
37        # Set the application manager for the GUI
38        self.gui.set_manager(self)
39        # Add perspectives to the basic application
40        # Additional perspectives can still be loaded
41        # dynamically
42        # Note: py2exe can't find dynamically loaded
43        # modules. We load the fitting module here
44        # to ensure a complete Windows executable build.
45
46        # Fitting perspective
47        try:
48            import sas.sasgui.perspectives.fitting as module
49            fitting_plug = module.Plugin()
50            self.gui.add_perspective(fitting_plug)
51        except Exception:
52            logger.error("%s: could not find Fitting plug-in module", APP_NAME)
53            logger.error(traceback.format_exc())
54
55        # P(r) perspective
56        try:
57            import sas.sasgui.perspectives.pr as module
58            pr_plug = module.Plugin()
59            self.gui.add_perspective(pr_plug)
60        except Exception:
61            logger.error("%s: could not find P(r) plug-in module", APP_NAME)
62            logger.error(traceback.format_exc())
63
64        # Invariant perspective
65        try:
66            import sas.sasgui.perspectives.invariant as module
67            invariant_plug = module.Plugin()
68            self.gui.add_perspective(invariant_plug)
69        except Exception:
70            logger.error("%s: could not find Invariant plug-in module",
71                         APP_NAME)
72            logger.error(traceback.format_exc())
73
74        # Corfunc perspective
75        try:
76            import sas.sasgui.perspectives.corfunc as module
77            corfunc_plug = module.Plugin()
78            self.gui.add_perspective(corfunc_plug)
79        except Exception:
80            logger.error("Unable to load corfunc module")
81
82        # Calculator perspective
83        try:
84            import sas.sasgui.perspectives.calculator as module
85            calculator_plug = module.Plugin()
86            self.gui.add_perspective(calculator_plug)
87        except Exception:
88            logger.error("%s: could not find Calculator plug-in module",
89                         APP_NAME)
90            logger.error(traceback.format_exc())
91
92        # File converter tool
93        try:
94            import sas.sasgui.perspectives.file_converter as module
95            converter_plug = module.Plugin()
96            self.gui.add_perspective(converter_plug)
97        except Exception:
98            logger.error("%s: could not find File Converter plug-in module",
99                         APP_NAME)
100            logger.error(traceback.format_exc())
101
102        # Add welcome page
103        from .welcome_panel import WelcomePanel
104        self.gui.set_welcome_panel(WelcomePanel)
105
106        # Build the GUI
107        self.gui.build_gui()
108        # delete unused model folder
109        self.gui.clean_plugin_models(PLUGIN_MODEL_DIR)
110        # Start the main loop
111        self.gui.MainLoop()
112
113
114def setup_logging():
115    from sas.logger_config import SetupLogger
116
117    logger = SetupLogger(__name__).config_production()
118    # Log the start of the session
119    logger.info(" --- SasView session started ---")
120    # Log the python version
121    logger.info("Python: %s" % sys.version)
122    return logger
123
124
125def setup_wx():
126    # Allow the dynamic selection of wxPython via an environment variable, when devs
127    # who have multiple versions of the module installed want to pick between them.
128    # This variable does not have to be set of course, and through normal usage will
129    # probably not be, but this can make things a little easier when upgrading to a
130    # new version of wx.
131    logger = logging.getLogger(__name__)
132    WX_ENV_VAR = "SASVIEW_WX_VERSION"
133    if WX_ENV_VAR in os.environ:
134        logger.info("You have set the %s environment variable to %s.",
135                    WX_ENV_VAR, os.environ[WX_ENV_VAR])
136        import wxversion
137        if wxversion.checkInstalled(os.environ[WX_ENV_VAR]):
138            logger.info("Version %s of wxPython is installed, so using that version.",
139                        os.environ[WX_ENV_VAR])
140            wxversion.select(os.environ[WX_ENV_VAR])
141        else:
142            logger.error("Version %s of wxPython is not installed, so using default version.",
143                         os.environ[WX_ENV_VAR])
144    else:
145        logger.info("You have not set the %s environment variable, so using default version of wxPython.",
146                    WX_ENV_VAR)
147
148    import wx
149
150    try:
151        logger.info("Wx version: %s", wx.__version__)
152    except AttributeError:
153        logger.error("Wx version: error reading version")
154
155    from . import wxcruft
156    wxcruft.call_later_fix()
157    #wxcruft.trace_new_id()
158    #Always use private .matplotlib setup to avoid conflicts with other
159    #uses of matplotlib
160
161
162def setup_mpl(backend='WXAgg'):
163    import sas.sasgui
164    # Always use private .matplotlib setup to avoid conflicts with other
165    mplconfigdir = os.path.join(sas.sasgui.get_user_dir(), '.matplotlib')
166    if not os.path.exists(mplconfigdir):
167        os.mkdir(mplconfigdir)
168    os.environ['MPLCONFIGDIR'] = mplconfigdir
169    # Set backend to WXAgg; this overrides matplotlibrc, but shouldn't override
170    # mpl.use().  Note: Don't import matplotlib here since the script that
171    # we are running may not actually need it; also, putting as little on the
172    # path as we can
173    os.environ['MPLBACKEND'] = backend
174
175    # TODO: ... so much for not importing matplotlib unless we need it...
176    from matplotlib import backend_bases
177    backend_bases.FigureCanvasBase.filetypes.pop('pgf', None)
178
179def setup_sasmodels():
180    """
181    Prepare sasmodels for running within sasview.
182    """
183    import sas.sasgui
184    # Set SAS_MODELPATH so sasmodels can find our custom models
185    plugin_dir = os.path.join(sas.sasgui.get_user_dir(), PLUGIN_MODEL_DIR)
186    os.environ['SAS_MODELPATH'] = plugin_dir
187    # TODO: SAS_OPENCL flag belongs in setup_sasmodels
188    # this will require restructuring of the config management so that it
189    # can occur outside of sasgui.
190
191def run_gui():
192    """
193    __main__ method for loading and running SasView
194    """
195    from multiprocessing import freeze_support
196    freeze_support()
197    setup_logging()
198    setup_mpl()
199    setup_sasmodels()
200    setup_wx()
201    SasView()
202
203
204def run_cli():
205    from multiprocessing import freeze_support
206    freeze_support()
207    setup_logging()
208    setup_mpl(backend='Agg')
209    setup_sasmodels()
210    if len(sys.argv) == 1:
211        # Run sasview as an interactive python interpreter
212        try:
213            from IPython import start_ipython
214            sys.argv = ["ipython", "--pylab"]
215            sys.exit(start_ipython())
216        except ImportError:
217            import code
218            code.interact(local={'exit': sys.exit})
219    else:
220        # Run sasview as a python script interpreter
221        ## Run sasview as an interactive python interpreter
222        # if sys.argv[1] == "-i":
223        #    sys.argv = ["ipython", "--pylab"]
224        #    from IPython import start_ipython
225        #    sys.exit(start_ipython())
226        thing_to_run = sys.argv[1]
227        sys.argv = sys.argv[1:]
228        import runpy
229        if os.path.exists(thing_to_run):
230            runpy.run_path(thing_to_run, run_name="__main__")
231        else:
232            runpy.run_module(thing_to_run, run_name="__main__")
233
234
235if __name__ == "__main__":
236    run_gui()
Note: See TracBrowser for help on using the repository browser.