source: sasview/src/sas/qtgui/GuiUtils.py @ 9e426c1

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 9e426c1 was 9e426c1, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 8 years ago

More main window items, system close, update checker, doc viewer etc.

  • Property mode set to 100755
File size: 10.5 KB
Line 
1"""
2    Global defaults and various utility functions usable by the general GUI
3"""
4
5import os
6import sys
7import time
8import imp
9import warnings
10import re
11warnings.simplefilter("ignore")
12import logging
13import traceback
14
15from PyQt4 import QtCore
16from PyQt4 import QtGui
17
18# Translate event handlers
19#from sas.sasgui.guiframe.events import EVT_CATEGORY
20#from sas.sasgui.guiframe.events import EVT_STATUS
21#from sas.sasgui.guiframe.events import EVT_APPEND_BOOKMARK
22#from sas.sasgui.guiframe.events import EVT_PANEL_ON_FOCUS
23#from sas.sasgui.guiframe.events import EVT_NEW_LOAD_DATA
24#from sas.sasgui.guiframe.events import EVT_NEW_COLOR
25#from sas.sasgui.guiframe.events import StatusEvent
26#from sas.sasgui.guiframe.events import NewPlotEvent
27from sas.sasgui.guiframe.dataFitting import Data1D
28from sas.sasgui.guiframe.dataFitting import Data2D
29
30
31def get_app_dir():
32    """
33        The application directory is the one where the default custom_config.py
34        file resides.
35
36        :returns: app_path - the path to the applicatin directory
37    """
38    # First, try the directory of the executable we are running
39    app_path = sys.path[0]
40    if os.path.isfile(app_path):
41        app_path = os.path.dirname(app_path)
42    if os.path.isfile(os.path.join(app_path, "custom_config.py")):
43        app_path = os.path.abspath(app_path)
44        logging.info("Using application path: %s", app_path)
45        return app_path
46
47    # Next, try the current working directory
48    if os.path.isfile(os.path.join(os.getcwd(), "custom_config.py")):
49        logging.info("Using application path: %s", os.getcwd())
50        return os.path.abspath(os.getcwd())
51
52    # Finally, try the directory of the sasview module
53    # TODO: gui_manager will have to know about sasview until we
54    # clean all these module variables and put them into a config class
55    # that can be passed by sasview.py.
56    logging.info(sys.executable)
57    logging.info(str(sys.argv))
58    from sas import sasview as sasview
59    app_path = os.path.dirname(sasview.__file__)
60    logging.info("Using application path: %s", app_path)
61    return app_path
62
63def get_user_directory():
64    """
65        Returns the user's home directory
66    """
67    userdir = os.path.join(os.path.expanduser("~"), ".sasview")
68    if not os.path.isdir(userdir):
69        os.makedirs(userdir)
70    return userdir
71
72def _find_local_config(file, path):
73    """
74        Find configuration file for the current application
75    """
76    config_module = None
77    fObj = None
78    try:
79        fObj, path_config, descr = imp.find_module(file, [path])
80        config_module = imp.load_module(file, fObj, path_config, descr)
81    except:
82        logging.error("Error loading %s/%s: %s" % (path, file, sys.exc_value))
83    finally:
84        if fObj is not None:
85            fObj.close()
86    logging.info("GuiManager loaded %s/%s" % (path, file))
87    return config_module
88
89# Get APP folder
90PATH_APP = get_app_dir()
91DATAPATH = PATH_APP
92
93# GUI always starts from the App folder
94#os.chdir(PATH_APP)
95# Read in the local config, which can either be with the main
96# application or in the installation directory
97config = _find_local_config('local_config', PATH_APP)
98if config is None:
99    config = _find_local_config('local_config', os.getcwd())
100    if config is None:
101        # Didn't find local config, load the default
102        import sas.sasgui.guiframe.config as config
103        logging.info("using default local_config")
104    else:
105        logging.info("found local_config in %s" % os.getcwd())
106else:
107    logging.info("found local_config in %s" % PATH_APP)
108
109
110from sas.sasgui.guiframe.customdir  import SetupCustom
111c_conf_dir = SetupCustom().setup_dir(PATH_APP)
112custom_config = _find_local_config('custom_config', c_conf_dir)
113if custom_config is None:
114    custom_config = _find_local_config('custom_config', os.getcwd())
115    if custom_config is None:
116        msgConfig = "Custom_config file was not imported"
117        logging.info(msgConfig)
118    else:
119        logging.info("using custom_config in %s" % os.getcwd())
120else:
121    logging.info("using custom_config from %s" % c_conf_dir)
122
123#read some constants from config
124APPLICATION_STATE_EXTENSION = config.APPLICATION_STATE_EXTENSION
125APPLICATION_NAME = config.__appname__
126SPLASH_SCREEN_PATH = config.SPLASH_SCREEN_PATH
127WELCOME_PANEL_ON = config.WELCOME_PANEL_ON
128SPLASH_SCREEN_WIDTH = config.SPLASH_SCREEN_WIDTH
129SPLASH_SCREEN_HEIGHT = config.SPLASH_SCREEN_HEIGHT
130SS_MAX_DISPLAY_TIME = config.SS_MAX_DISPLAY_TIME
131if not WELCOME_PANEL_ON:
132    WELCOME_PANEL_SHOW = False
133else:
134    WELCOME_PANEL_SHOW = True
135try:
136    DATALOADER_SHOW = custom_config.DATALOADER_SHOW
137    TOOLBAR_SHOW = custom_config.TOOLBAR_SHOW
138    FIXED_PANEL = custom_config.FIXED_PANEL
139    if WELCOME_PANEL_ON:
140        WELCOME_PANEL_SHOW = custom_config.WELCOME_PANEL_SHOW
141    PLOPANEL_WIDTH = custom_config.PLOPANEL_WIDTH
142    DATAPANEL_WIDTH = custom_config.DATAPANEL_WIDTH
143    GUIFRAME_WIDTH = custom_config.GUIFRAME_WIDTH
144    GUIFRAME_HEIGHT = custom_config.GUIFRAME_HEIGHT
145    CONTROL_WIDTH = custom_config.CONTROL_WIDTH
146    CONTROL_HEIGHT = custom_config.CONTROL_HEIGHT
147    DEFAULT_PERSPECTIVE = custom_config.DEFAULT_PERSPECTIVE
148    CLEANUP_PLOT = custom_config.CLEANUP_PLOT
149    # custom open_path
150    open_folder = custom_config.DEFAULT_OPEN_FOLDER
151    if open_folder != None and os.path.isdir(open_folder):
152        DEFAULT_OPEN_FOLDER = os.path.abspath(open_folder)
153    else:
154        DEFAULT_OPEN_FOLDER = PATH_APP
155except:
156    DATALOADER_SHOW = True
157    TOOLBAR_SHOW = True
158    FIXED_PANEL = True
159    WELCOME_PANEL_SHOW = False
160    PLOPANEL_WIDTH = config.PLOPANEL_WIDTH
161    DATAPANEL_WIDTH = config.DATAPANEL_WIDTH
162    GUIFRAME_WIDTH = config.GUIFRAME_WIDTH
163    GUIFRAME_HEIGHT = config.GUIFRAME_HEIGHT
164    CONTROL_WIDTH = -1
165    CONTROL_HEIGHT = -1
166    DEFAULT_PERSPECTIVE = None
167    CLEANUP_PLOT = False
168    DEFAULT_OPEN_FOLDER = PATH_APP
169
170DEFAULT_STYLE = config.DEFAULT_STYLE
171
172PLUGIN_STATE_EXTENSIONS = config.PLUGIN_STATE_EXTENSIONS
173OPEN_SAVE_MENU = config.OPEN_SAVE_PROJECT_MENU
174VIEW_MENU = config.VIEW_MENU
175EDIT_MENU = config.EDIT_MENU
176extension_list = []
177if APPLICATION_STATE_EXTENSION is not None:
178    extension_list.append(APPLICATION_STATE_EXTENSION)
179EXTENSIONS = PLUGIN_STATE_EXTENSIONS + extension_list
180try:
181    PLUGINS_WLIST = '|'.join(config.PLUGINS_WLIST)
182except:
183    PLUGINS_WLIST = ''
184APPLICATION_WLIST = config.APPLICATION_WLIST
185IS_WIN = True
186IS_LINUX = False
187CLOSE_SHOW = True
188TIME_FACTOR = 2
189NOT_SO_GRAPH_LIST = ["BoxSum"]
190
191class Communicate(QtCore.QObject):
192    """
193    Utility class for tracking of the Qt signals
194    """
195    # File got successfully read
196    fileReadSignal = QtCore.pyqtSignal(list)
197
198    # Open File returns "list" of paths
199    fileDataReceivedSignal = QtCore.pyqtSignal(dict)
200
201    # Update Main window status bar with "str"
202    statusBarUpdateSignal = QtCore.pyqtSignal(str)
203
204    # Send data to the current perspective
205    updatePerspectiveWithDataSignal = QtCore.pyqtSignal(list)
206
207    # New data in current perspective
208    updateModelFromPerspectiveSignal = QtCore.pyqtSignal(QtGui.QStandardItem)
209
210def updateModelItem(item, update_data, name=""):
211    """
212    Adds a checkboxed row named "name" to QStandardItem
213    Adds QVariant 'update_data' to that row.
214    """
215    assert type(item) == QtGui.QStandardItem
216    assert type(update_data) == QtCore.QVariant
217
218    checkbox_item = QtGui.QStandardItem(True)
219    checkbox_item.setCheckable(True)
220    checkbox_item.setCheckState(QtCore.Qt.Checked)
221    checkbox_item.setText(name)
222
223    # Add "Info" item
224    py_update_data = update_data.toPyObject()
225    if type(py_update_data) == (Data1D or Data2D):
226        # If Data1/2D added - extract Info from it
227        info_item = infoFromData(py_update_data)
228    else:
229        # otherwise just add a naked item
230        info_item = QtGui.QStandardItem("Info")       
231
232    # Add the actual Data1D/Data2D object
233    object_item = QtGui.QStandardItem()
234    object_item.setData(update_data)
235
236    # Set the data object as the first child
237    checkbox_item.setChild(0, object_item)
238
239    # Set info_item as the second child
240    checkbox_item.setChild(1, info_item)
241
242    # Append the new row to the main item
243    item.appendRow(checkbox_item)
244
245def plotsFromCheckedItems(model_item):
246    """
247    Returns the list of plots for items in the model which are checked
248    """
249    assert type(model_item) == QtGui.QStandardItemModel
250
251    checkbox_item = QtGui.QStandardItem(True)
252    plot_data = []
253
254    # Iterate over model looking for items with checkboxes
255    for index in range(model_item.rowCount()):
256        item = model_item.item(index)
257        if item.isCheckable() and item.checkState() == QtCore.Qt.Checked:
258            # TODO: assure item type is correct (either data1/2D or Plotter)
259            plot_data.append(item.child(0).data().toPyObject())
260        # Going 1 level deeper only
261        for index_2 in range(item.rowCount()):
262            item_2 = item.child(index_2)
263            if item_2 and item_2.isCheckable() and item_2.checkState() == QtCore.Qt.Checked:
264                # TODO: assure item type is correct (either data1/2D or Plotter)
265                plot_data.append(item_2.child(0).data().toPyObject())
266 
267    return plot_data
268
269def infoFromData(data):
270    """
271    Given Data1D/Data2D object, extract relevant Info elements
272    and add them to a model item
273    """
274    assert type(data) in [Data1D, Data2D]
275
276    info_item = QtGui.QStandardItem("Info")
277
278    title_item   = QtGui.QStandardItem("Title: "      + data.title)
279    info_item.appendRow(title_item)
280    run_item     = QtGui.QStandardItem("Run: "        + str(data.run))
281    info_item.appendRow(run_item)
282    type_item    = QtGui.QStandardItem("Type: "       + str(data.__class__.__name__))
283    info_item.appendRow(type_item)
284
285    if data.path:
286        path_item    = QtGui.QStandardItem("Path: "       + data.path)
287        info_item.appendRow(path_item)
288
289    if data.instrument:
290        instr_item   = QtGui.QStandardItem("Instrument: " + data.instrument)
291        info_item.appendRow(instr_item)
292
293    process_item = QtGui.QStandardItem("Process")
294    if isinstance(data.process, list) and data.process:
295        for process in data.process:
296            process_date = process.date
297            process_date_item = QtGui.QStandardItem("Date: " + process_date)
298            process_item.appendRow(process_date_item)
299
300            process_descr = process.description
301            process_descr_item = QtGui.QStandardItem("Description: " + process_descr)
302            process_item.appendRow(process_descr_item)
303
304            process_name = process.name
305            process_name_item = QtGui.QStandardItem("Name: " + process_name)
306            process_item.appendRow(process_name_item)
307
308    info_item.appendRow(process_item)
309
310    return info_item
311
Note: See TracBrowser for help on using the repository browser.