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

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 b796c72 was b796c72, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

Merge branch 'ticket-853-fit-gui-to-calc' into py3

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