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

magnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249unittest-saveload
Last change on this file since c82cf89 was c82cf89, checked in by wojciech, 6 years ago

Forcing cc check at installation that should trigger Xcode

  • Property mode set to 100644
File size: 9.6 KB
RevLine 
[7fb59b2]1# -*- coding: utf-8 -*-
[415fb82]2"""
3Base module for loading and running the main SasView application.
4"""
[f76bf17]5################################################################################
[f36e01f]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.
[f76bf17]9#
[f36e01f]10# See the license text in license.txt
[f76bf17]11#
[f36e01f]12# copyright 2009, University of Tennessee
[f76bf17]13################################################################################
14import os
[5af6f58]15import os.path
[f76bf17]16import sys
[4e080980]17import traceback
[7c105e8]18import logging
[4e080980]19
[0225a3f]20try:
21    reload(sys)
22    sys.setdefaultencoding("iso-8859-1")
23except NameError:
24    # On python 3 sys.setdefaultencoding does nothing, so pass.
25    # We know we are in python 3 at this point since reload is no longer in
26    # builtins, but instead has been moved to importlib, hence the NameError.
27    pass
[f36e01f]28
[b963b20]29import sas
30
[f76bf17]31APP_NAME = 'SasView'
[1693141]32PLUGIN_MODEL_DIR = 'plugin_models'
[f76bf17]33
[1693141]34class SasView(object):
[f76bf17]35    """
[415fb82]36    Main class for running the SasView application
[f76bf17]37    """
38    def __init__(self):
39        """
40        """
[7c105e8]41        logger = logging.getLogger(__name__)
42
[899e084]43        from sas.sasgui.guiframe.gui_manager import SasViewApp
44        self.gui = SasViewApp(0)
[f76bf17]45        # Set the application manager for the GUI
46        self.gui.set_manager(self)
47        # Add perspectives to the basic application
48        # Additional perspectives can still be loaded
49        # dynamically
50        # Note: py2exe can't find dynamically loaded
51        # modules. We load the fitting module here
52        # to ensure a complete Windows executable build.
53
[65f3930]54        # Rebuild .sasview/categories.json.  This triggers a load of sasmodels
55        # and all the plugins.
56        try:
57            from sas.sascalc.fit.models import ModelManager
58            from sas.sasgui.guiframe.CategoryInstaller import CategoryInstaller
59            model_list = ModelManager().cat_model_list()
60            CategoryInstaller.check_install(model_list=model_list)
61        except Exception:
62            logger.error("%s: could not load SasView models")
63            logger.error(traceback.format_exc())
64
[f76bf17]65        # Fitting perspective
66        try:
[77d92cd]67            import sas.sasgui.perspectives.fitting as module
[f76bf17]68            fitting_plug = module.Plugin()
69            self.gui.add_perspective(fitting_plug)
[415fb82]70        except Exception:
[b39d32d5]71            logger.error("%s: could not find Fitting plug-in module", APP_NAME)
[64ca561]72            logger.error(traceback.format_exc())
[f76bf17]73
74        # P(r) perspective
75        try:
[d85c194]76            import sas.sasgui.perspectives.pr as module
[f21d496]77            pr_plug = module.Plugin()
[f76bf17]78            self.gui.add_perspective(pr_plug)
[b39d32d5]79        except Exception:
80            logger.error("%s: could not find P(r) plug-in module", APP_NAME)
[64ca561]81            logger.error(traceback.format_exc())
[4e080980]82
[f36e01f]83        # Invariant perspective
[f76bf17]84        try:
[d85c194]85            import sas.sasgui.perspectives.invariant as module
[f21d496]86            invariant_plug = module.Plugin()
[f76bf17]87            self.gui.add_perspective(invariant_plug)
[b39d32d5]88        except Exception:
89            logger.error("%s: could not find Invariant plug-in module",
90                         APP_NAME)
[64ca561]91            logger.error(traceback.format_exc())
[4e080980]92
[c23f303]93        # Corfunc perspective
94        try:
95            import sas.sasgui.perspectives.corfunc as module
96            corfunc_plug = module.Plugin()
97            self.gui.add_perspective(corfunc_plug)
[b39d32d5]98        except Exception:
[64ca561]99            logger.error("Unable to load corfunc module")
[c23f303]100
[f36e01f]101        # Calculator perspective
[f76bf17]102        try:
[d85c194]103            import sas.sasgui.perspectives.calculator as module
[f21d496]104            calculator_plug = module.Plugin()
[f76bf17]105            self.gui.add_perspective(calculator_plug)
[b39d32d5]106        except Exception:
107            logger.error("%s: could not find Calculator plug-in module",
108                         APP_NAME)
[64ca561]109            logger.error(traceback.format_exc())
[4e080980]110
[77d92cd]111        # File converter tool
112        try:
113            import sas.sasgui.perspectives.file_converter as module
114            converter_plug = module.Plugin()
115            self.gui.add_perspective(converter_plug)
[b39d32d5]116        except Exception:
117            logger.error("%s: could not find File Converter plug-in module",
118                         APP_NAME)
[64ca561]119            logger.error(traceback.format_exc())
[77d92cd]120
[f76bf17]121        # Add welcome page
[899e084]122        from .welcome_panel import WelcomePanel
[f76bf17]123        self.gui.set_welcome_panel(WelcomePanel)
[415fb82]124
[f76bf17]125        # Build the GUI
126        self.gui.build_gui()
[415fb82]127        # delete unused model folder
[f76bf17]128        self.gui.clean_plugin_models(PLUGIN_MODEL_DIR)
129        # Start the main loop
130        self.gui.MainLoop()
131
132
[899e084]133def setup_logging():
[7c105e8]134    from sas.logger_config import SetupLogger
[899e084]135
[7c105e8]136    logger = SetupLogger(__name__).config_production()
[899e084]137    # Log the start of the session
[7c105e8]138    logger.info(" --- SasView session started ---")
[899e084]139    # Log the python version
[7c105e8]140    logger.info("Python: %s" % sys.version)
141    return logger
[899e084]142
143
144def setup_wx():
145    # Allow the dynamic selection of wxPython via an environment variable, when devs
146    # who have multiple versions of the module installed want to pick between them.
147    # This variable does not have to be set of course, and through normal usage will
148    # probably not be, but this can make things a little easier when upgrading to a
149    # new version of wx.
[7c105e8]150    logger = logging.getLogger(__name__)
[899e084]151    WX_ENV_VAR = "SASVIEW_WX_VERSION"
152    if WX_ENV_VAR in os.environ:
[b39d32d5]153        logger.info("You have set the %s environment variable to %s.",
154                    WX_ENV_VAR, os.environ[WX_ENV_VAR])
[899e084]155        import wxversion
156        if wxversion.checkInstalled(os.environ[WX_ENV_VAR]):
[b39d32d5]157            logger.info("Version %s of wxPython is installed, so using that version.",
158                        os.environ[WX_ENV_VAR])
[899e084]159            wxversion.select(os.environ[WX_ENV_VAR])
160        else:
[b39d32d5]161            logger.error("Version %s of wxPython is not installed, so using default version.",
162                         os.environ[WX_ENV_VAR])
[899e084]163    else:
[b39d32d5]164        logger.info("You have not set the %s environment variable, so using default version of wxPython.",
165                    WX_ENV_VAR)
[899e084]166
167    import wx
168
169    try:
[b39d32d5]170        logger.info("Wx version: %s", wx.__version__)
171    except AttributeError:
[914ba0a]172        logger.error("Wx version: error reading version")
[899e084]173
174    from . import wxcruft
175    wxcruft.call_later_fix()
176    #wxcruft.trace_new_id()
177    #Always use private .matplotlib setup to avoid conflicts with other
178    #uses of matplotlib
179
180
[b963b20]181def setup_mpl(backend=None):
[914ba0a]182    # Always use private .matplotlib setup to avoid conflicts with other
[b963b20]183    mplconfigdir = os.path.join(sas.get_user_dir(), '.matplotlib')
[899e084]184    if not os.path.exists(mplconfigdir):
185        os.mkdir(mplconfigdir)
186    os.environ['MPLCONFIGDIR'] = mplconfigdir
187    # Set backend to WXAgg; this overrides matplotlibrc, but shouldn't override
188    # mpl.use().  Note: Don't import matplotlib here since the script that
189    # we are running may not actually need it; also, putting as little on the
190    # path as we can
[b277220]191    if backend:
192        os.environ['MPLBACKEND'] = backend
[899e084]193
[1693141]194    # TODO: ... so much for not importing matplotlib unless we need it...
[914ba0a]195    from matplotlib import backend_bases
196    backend_bases.FigureCanvasBase.filetypes.pop('pgf', None)
197
[0a5d1a8]198def check_sasmodels_compiler():
[1693141]199    """
[c82cf89]200    Checking c compiler for sasmodels and trying to trigger xcode command line
201    for installation
[1693141]202    """
[c82cf89]203    import subprocess
204    logger = logging.getLogger(__name__)
205    #if sys.platform == "darwin" and not\
206    try:
207        # need shell=True on windows to keep console box from popping up
208        shell = (os.name == 'nt')
209        subprocess.check_output("cc", shell=shell, stderr=subprocess.STDOUT)
210    except subprocess.CalledProcessError:
211        raise RuntimeError("No compiler installed. Please follow installation instructions\n")
[0a5d1a8]212
213def setup_sasmodels():
214    """
215    Prepare sasmodels for running within sasview.
216    """
[1693141]217    # Set SAS_MODELPATH so sasmodels can find our custom models
[b963b20]218    plugin_dir = os.path.join(sas.get_user_dir(), PLUGIN_MODEL_DIR)
[1693141]219    os.environ['SAS_MODELPATH'] = plugin_dir
[20fa5fe]220    #Initialize environment variable with custom setting but only if variable not set
[b963b20]221    SAS_OPENCL = sas.get_custom_config().SAS_OPENCL
222    if SAS_OPENCL and "SAS_OPENCL" not in os.environ:
223        os.environ["SAS_OPENCL"] = SAS_OPENCL
[60a7820]224
[899e084]225def run_gui():
[415fb82]226    """
227    __main__ method for loading and running SasView
228    """
[f76bf17]229    from multiprocessing import freeze_support
230    freeze_support()
[899e084]231    setup_logging()
[b963b20]232    setup_mpl(backend='WXAgg')
[1693141]233    setup_sasmodels()
234    setup_wx()
[c82cf89]235    check_sasmodels_compiler()
[899e084]236    SasView()
237
238
239def run_cli():
[1693141]240    from multiprocessing import freeze_support
241    freeze_support()
[7c105e8]242    setup_logging()
[b963b20]243    # Use default matplotlib backend on mac/linux, but wx on windows.
244    # The problem on mac is that the wx backend requires pythonw.  On windows
245    # we are sure to wx since it is the shipped with the app.
246    setup_mpl(backend='WXAgg' if os.name == 'nt' else None)
[1693141]247    setup_sasmodels()
[aaa801e]248    if len(sys.argv) == 1 or sys.argv[1] == '-i':
[899e084]249        # Run sasview as an interactive python interpreter
[4b26bc14]250        try:
251            from IPython import start_ipython
252            sys.argv = ["ipython", "--pylab"]
253            sys.exit(start_ipython())
254        except ImportError:
255            import code
[b39d32d5]256            code.interact(local={'exit': sys.exit})
[0225a3f]257    elif sys.argv[1] == '-c':
258        exec(sys.argv[2])
[899e084]259    else:
[f76bf17]260        thing_to_run = sys.argv[1]
261        sys.argv = sys.argv[1:]
262        import runpy
263        if os.path.exists(thing_to_run):
264            runpy.run_path(thing_to_run, run_name="__main__")
265        else:
266            runpy.run_module(thing_to_run, run_name="__main__")
267
[f36e01f]268
[f76bf17]269if __name__ == "__main__":
[899e084]270    run_gui()
Note: See TracBrowser for help on using the repository browser.