source: sasview/src/sas/sasview/sasview.py @ 914ba0a

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

merge with master

  • Property mode set to 100644
File size: 7.7 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
18
19from sas.sasview.logger_config import SetupLogger
20
21reload(sys)
22sys.setdefaultencoding("iso-8859-1")
23
24logger = SetupLogger(__name__).config_production()
25# Log the start of the session
26logger.info(" --- SasView session started ---")
27# Log the python version
28logger.info("Python: %s" % sys.version)
29
30
31PLUGIN_MODEL_DIR = 'plugin_models'
32APP_NAME = 'SasView'
33
34class SasView():
35    """
36    Main class for running the SasView application
37    """
38    def __init__(self):
39        """
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:
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 as e :
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:
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:
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:
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    log_file = os.path.join(os.path.expanduser("~"), 'sasview.log')
122    logging.basicConfig(level=logging.INFO,
123                        format='%(asctime)s %(levelname)s %(message)s',
124                        filename=log_file,
125                        )
126    logging.captureWarnings(True)
127
128    stderr_logger = logging.getLogger('STDERR')
129    sl = StreamToLogger(stderr_logger, logging.ERROR)
130    sys.stderr = sl
131
132    # Log the start of the session
133    logging.info(" --- SasView session started ---")
134
135    # Log the python version
136    logging.info("Python: %s" % sys.version)
137
138
139def setup_wx():
140    # Allow the dynamic selection of wxPython via an environment variable, when devs
141    # who have multiple versions of the module installed want to pick between them.
142    # This variable does not have to be set of course, and through normal usage will
143    # probably not be, but this can make things a little easier when upgrading to a
144    # new version of wx.
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." % os.environ[WX_ENV_VAR])
152            wxversion.select(os.environ[WX_ENV_VAR])
153        else:
154            logger.error("Version %s of wxPython is not installed, so using default version." % os.environ[WX_ENV_VAR])
155    else:
156        logger.info("You have not set the %s environment variable, so using default version of wxPython." % WX_ENV_VAR)
157
158    import wx
159
160    try:
161        logger.info("Wx version: %s" % wx.__version__)
162    except:
163        logger.error("Wx version: error reading version")
164
165    from . import wxcruft
166    wxcruft.call_later_fix()
167    #wxcruft.trace_new_id()
168    #Always use private .matplotlib setup to avoid conflicts with other
169    #uses of matplotlib
170
171
172def setup_mpl():
173    import sas.sasgui
174    # Always use private .matplotlib setup to avoid conflicts with other
175    mplconfigdir = os.path.join(sas.sasgui.get_user_dir(), '.matplotlib')
176    if not os.path.exists(mplconfigdir):
177        os.mkdir(mplconfigdir)
178    os.environ['MPLCONFIGDIR'] = mplconfigdir
179    # Set backend to WXAgg; this overrides matplotlibrc, but shouldn't override
180    # mpl.use().  Note: Don't import matplotlib here since the script that
181    # we are running may not actually need it; also, putting as little on the
182    # path as we can
183    os.environ['MPLBACKEND'] = 'WXAgg'
184
185
186    from matplotlib import backend_bases
187    backend_bases.FigureCanvasBase.filetypes.pop('pgf', None)
188
189def run_gui():
190    """
191    __main__ method for loading and running SasView
192    """
193    from multiprocessing import freeze_support
194    freeze_support()
195    setup_logging()
196    setup_wx()
197    setup_mpl()
198    SasView()
199
200
201def run_cli():
202    setup_mpl()
203    if len(sys.argv) == 1:
204        # Run sasview as an interactive python interpreter
205        sys.argv = ["ipython", "--pylab"]
206        from IPython import start_ipython
207        sys.exit(start_ipython())
208    else:
209        # Run sasview as a python script interpreter
210        ## Run sasview as an interactive python interpreter
211        # if sys.argv[1] == "-i":
212        #    sys.argv = ["ipython", "--pylab"]
213        #    from IPython import start_ipython
214        #    sys.exit(start_ipython())
215        thing_to_run = sys.argv[1]
216        sys.argv = sys.argv[1:]
217        import runpy
218        if os.path.exists(thing_to_run):
219            runpy.run_path(thing_to_run, run_name="__main__")
220        else:
221            runpy.run_module(thing_to_run, run_name="__main__")
222
223
224if __name__ == "__main__":
225    run_gui()
Note: See TracBrowser for help on using the repository browser.