source: sasview/src/sas/sasview/sasview.py @ 47439ce

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

Generic message box implemented to support position change of dialog

  • Property mode set to 100644
File size: 10.5 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
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
28
29import sas
30
31APP_NAME = 'SasView'
32PLUGIN_MODEL_DIR = 'plugin_models'
33
34class SasView(object):
35    """
36    Main class for running the SasView application
37    """
38    def __init__(self):
39        """
40        """
41        logger = logging.getLogger(__name__)
42
43        from sas.sasgui.guiframe.gui_manager import SasViewApp
44        self.gui = SasViewApp(0)
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
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
65        # Fitting perspective
66        try:
67            import sas.sasgui.perspectives.fitting as module
68            fitting_plug = module.Plugin()
69            self.gui.add_perspective(fitting_plug)
70        except Exception:
71            logger.error("%s: could not find Fitting plug-in module", APP_NAME)
72            logger.error(traceback.format_exc())
73
74        # P(r) perspective
75        try:
76            import sas.sasgui.perspectives.pr as module
77            pr_plug = module.Plugin()
78            self.gui.add_perspective(pr_plug)
79        except Exception:
80            logger.error("%s: could not find P(r) plug-in module", APP_NAME)
81            logger.error(traceback.format_exc())
82
83        # Invariant perspective
84        try:
85            import sas.sasgui.perspectives.invariant as module
86            invariant_plug = module.Plugin()
87            self.gui.add_perspective(invariant_plug)
88        except Exception:
89            logger.error("%s: could not find Invariant plug-in module",
90                         APP_NAME)
91            logger.error(traceback.format_exc())
92
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)
98        except Exception:
99            logger.error("Unable to load corfunc module")
100
101        # Calculator perspective
102        try:
103            import sas.sasgui.perspectives.calculator as module
104            calculator_plug = module.Plugin()
105            self.gui.add_perspective(calculator_plug)
106        except Exception:
107            logger.error("%s: could not find Calculator plug-in module",
108                         APP_NAME)
109            logger.error(traceback.format_exc())
110
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)
116        except Exception:
117            logger.error("%s: could not find File Converter plug-in module",
118                         APP_NAME)
119            logger.error(traceback.format_exc())
120
121        # Add welcome page
122        from .welcome_panel import WelcomePanel
123        self.gui.set_welcome_panel(WelcomePanel)
124
125        # Build the GUI
126        self.gui.build_gui()
127        # delete unused model folder
128        self.gui.clean_plugin_models(PLUGIN_MODEL_DIR)
129        # Start the main loop
130        self.gui.MainLoop()
131
132
133def setup_logging():
134    from sas.logger_config import SetupLogger
135
136    logger = SetupLogger(__name__).config_production()
137    # Log the start of the session
138    logger.info(" --- SasView session started ---")
139    # Log the python version
140    logger.info("Python: %s" % sys.version)
141    return logger
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.
150    logger = logging.getLogger(__name__)
151    WX_ENV_VAR = "SASVIEW_WX_VERSION"
152    if WX_ENV_VAR in os.environ:
153        logger.info("You have set the %s environment variable to %s.",
154                    WX_ENV_VAR, os.environ[WX_ENV_VAR])
155        import wxversion
156        if wxversion.checkInstalled(os.environ[WX_ENV_VAR]):
157            logger.info("Version %s of wxPython is installed, so using that version.",
158                        os.environ[WX_ENV_VAR])
159            wxversion.select(os.environ[WX_ENV_VAR])
160        else:
161            logger.error("Version %s of wxPython is not installed, so using default version.",
162                         os.environ[WX_ENV_VAR])
163    else:
164        logger.info("You have not set the %s environment variable, so using default version of wxPython.",
165                    WX_ENV_VAR)
166
167    import wx
168
169    try:
170        logger.info("Wx version: %s", wx.__version__)
171    except AttributeError:
172        logger.error("Wx version: error reading version")
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
181def setup_mpl(backend=None):
182    # Always use private .matplotlib setup to avoid conflicts with other
183    mplconfigdir = os.path.join(sas.get_user_dir(), '.matplotlib')
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
191    if backend:
192        os.environ['MPLBACKEND'] = backend
193
194    # TODO: ... so much for not importing matplotlib unless we need it...
195    from matplotlib import backend_bases
196    backend_bases.FigureCanvasBase.filetypes.pop('pgf', None)
197
198def check_sasmodels_compiler():
199    """
200    Checking c compiler for sasmodels and raises xcode command line
201    tools for installation
202    """
203    import wx
204    import subprocess
205    #Generic message box is nessary here becuase standard MessageBox is not moveable
206    class GenericMessageBox(wx.Dialog):
207        def __init__(self, parent, text, title = ''):
208            wx.Dialog.__init__(self, parent, -1, title = title,
209                               size = (360,140), pos=(20,20),
210                               style = wx.DEFAULT_DIALOG_STYLE )
211            panel = wx.Panel(self, wx.ID_ANY, size = (360, 100), pos = (0,0))
212            panel.SetBackgroundColour('#FFFFFF')
213            label = wx.StaticText(panel, -1, text, pos = (0,20))
214            panel2 = wx.Panel(self, wx.ID_ANY, size = (360, 40), pos = (0, 60))
215            btn = wx.Button(panel2, wx.ID_OK, pos = (250,7))
216            self.ShowModal()
217
218
219    logger = logging.getLogger(__name__)
220    try:
221        subprocess.check_output(["cc","--version"], stderr=subprocess.STDOUT)
222    except subprocess.CalledProcessError as exc:
223        app = wx.App()
224        dlg = GenericMessageBox(parent=None,
225            text='No compiler installed. Please follow instruction for\n '
226                'Xcode command line installation and restart SasView\n'
227                'SasView is terminating now\n',
228            title = 'Info')
229        dlg.Destroy()
230
231        logger.error("No compiler installed. %s\n"%(exc))
232        logger.error(traceback.format_exc())
233
234        raise RuntimeError("Terminating sasview")
235
236def setup_sasmodels():
237    """
238    Prepare sasmodels for running within sasview.
239    """
240    # Set SAS_MODELPATH so sasmodels can find our custom models
241    plugin_dir = os.path.join(sas.get_user_dir(), PLUGIN_MODEL_DIR)
242    os.environ['SAS_MODELPATH'] = plugin_dir
243    #Initialize environment variable with custom setting but only if variable not set
244    SAS_OPENCL = sas.get_custom_config().SAS_OPENCL
245    if SAS_OPENCL and "SAS_OPENCL" not in os.environ:
246        os.environ["SAS_OPENCL"] = SAS_OPENCL
247
248def run_gui():
249    """
250    __main__ method for loading and running SasView
251    """
252    from multiprocessing import freeze_support
253    freeze_support()
254    setup_logging()
255    setup_mpl(backend='WXAgg')
256    setup_sasmodels()
257    setup_wx()
258    if sys.platform == "darwin":
259        check_sasmodels_compiler()
260    SasView()
261
262
263def run_cli():
264    from multiprocessing import freeze_support
265    freeze_support()
266    setup_logging()
267    # Use default matplotlib backend on mac/linux, but wx on windows.
268    # The problem on mac is that the wx backend requires pythonw.  On windows
269    # we are sure to wx since it is the shipped with the app.
270    setup_mpl(backend='WXAgg' if os.name == 'nt' else None)
271    setup_sasmodels()
272    if len(sys.argv) == 1 or sys.argv[1] == '-i':
273        # Run sasview as an interactive python interpreter
274        try:
275            from IPython import start_ipython
276            sys.argv = ["ipython", "--pylab"]
277            sys.exit(start_ipython())
278        except ImportError:
279            import code
280            code.interact(local={'exit': sys.exit})
281    elif sys.argv[1] == '-c':
282        exec(sys.argv[2])
283    else:
284        thing_to_run = sys.argv[1]
285        sys.argv = sys.argv[1:]
286        import runpy
287        if os.path.exists(thing_to_run):
288            runpy.run_path(thing_to_run, run_name="__main__")
289        else:
290            runpy.run_module(thing_to_run, run_name="__main__")
291
292
293if __name__ == "__main__":
294    run_gui()
Note: See TracBrowser for help on using the repository browser.