source: sasview/src/sas/sasview/sasview.py @ 18b98f3

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

clean-up

  • Property mode set to 100644
File size: 11.2 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, -1)
212            top_row_sizer = wx.BoxSizer(wx.HORIZONTAL)
213
214            error_bitmap = wx.ArtProvider.GetBitmap(
215                wx.ART_ERROR, wx.ART_MESSAGE_BOX
216            )
217            error_bitmap_ctrl = wx.StaticBitmap(panel, -1)
218            error_bitmap_ctrl.SetBitmap(error_bitmap)
219            label = wx.StaticText(panel, -1, text)
220            top_row_sizer.Add(error_bitmap_ctrl, flag=wx.ALL, border=10)
221            top_row_sizer.Add(label, flag=wx.ALIGN_CENTER_VERTICAL)
222
223            #Create the OK button in the bottom row.
224            ok_button = wx.Button(panel, -1, 'OK')
225            self.Bind(wx.EVT_BUTTON, self.on_ok, source=ok_button)
226            ok_button.SetFocus()
227            ok_button.SetDefault()
228
229            sizer = wx.BoxSizer(wx.VERTICAL)
230            sizer.Add(top_row_sizer)
231            # sizer.Add(message_label, flag=wx.ALL | wx.EXPAND, border=10)
232            sizer.Add(ok_button, flag=wx.ALIGN_CENTER | wx.ALL, border=5)
233            panel.SetSizer(sizer)
234
235        def on_ok(self, event):
236            self.Destroy()
237
238    logger = logging.getLogger(__name__)
239    try:
240        subprocess.check_output(["cc","--version"], stderr=subprocess.STDOUT)
241    except subprocess.CalledProcessError as exc:
242        app = wx.App()
243        dlg = GenericMessageBox(parent=None,
244            text='No compiler installed. Please follow instruction for '
245                'Xcode command line installation and restart SasView'
246                'SasView is terminating now',
247            title = 'Compiler Info')
248        dlg.Destroy()
249
250        logger.error("No compiler installed. %s\n"%(exc))
251        logger.error(traceback.format_exc())
252
253        raise RuntimeError("Terminating sasview")
254
255def setup_sasmodels():
256    """
257    Prepare sasmodels for running within sasview.
258    """
259    # Set SAS_MODELPATH so sasmodels can find our custom models
260    plugin_dir = os.path.join(sas.get_user_dir(), PLUGIN_MODEL_DIR)
261    os.environ['SAS_MODELPATH'] = plugin_dir
262    #Initialize environment variable with custom setting but only if variable not set
263    SAS_OPENCL = sas.get_custom_config().SAS_OPENCL
264    if SAS_OPENCL and "SAS_OPENCL" not in os.environ:
265        os.environ["SAS_OPENCL"] = SAS_OPENCL
266
267def run_gui():
268    """
269    __main__ method for loading and running SasView
270    """
271    from multiprocessing import freeze_support
272    freeze_support()
273    setup_logging()
274    setup_mpl(backend='WXAgg')
275    setup_sasmodels()
276    setup_wx()
277    if sys.platform == "darwin":
278        check_sasmodels_compiler()
279    SasView()
280
281
282def run_cli():
283    from multiprocessing import freeze_support
284    freeze_support()
285    setup_logging()
286    # Use default matplotlib backend on mac/linux, but wx on windows.
287    # The problem on mac is that the wx backend requires pythonw.  On windows
288    # we are sure to wx since it is the shipped with the app.
289    setup_mpl(backend='WXAgg' if os.name == 'nt' else None)
290    setup_sasmodels()
291    if len(sys.argv) == 1 or sys.argv[1] == '-i':
292        # Run sasview as an interactive python interpreter
293        try:
294            from IPython import start_ipython
295            sys.argv = ["ipython", "--pylab"]
296            sys.exit(start_ipython())
297        except ImportError:
298            import code
299            code.interact(local={'exit': sys.exit})
300    elif sys.argv[1] == '-c':
301        exec(sys.argv[2])
302    else:
303        thing_to_run = sys.argv[1]
304        sys.argv = sys.argv[1:]
305        import runpy
306        if os.path.exists(thing_to_run):
307            runpy.run_path(thing_to_run, run_name="__main__")
308        else:
309            runpy.run_module(thing_to_run, run_name="__main__")
310
311
312if __name__ == "__main__":
313    run_gui()
Note: See TracBrowser for help on using the repository browser.