source: sasview/src/sas/sasview/sasview.py @ 706bb4e

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

Merge branch 'master' into ticket-887-reorg

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