source: sasview/src/sas/qtgui/GuiUtils.py @ 4b71e91

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 4b71e91 was 4b71e91, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 8 years ago

Context menu implementation p.1

  • Property mode set to 100755
File size: 14.2 KB
Line 
1"""
2    Global defaults and various utility functions usable by the general GUI
3"""
4
5import os
6import sys
7import imp
8import warnings
9import webbrowser
10import urlparse
11
12warnings.simplefilter("ignore")
13import logging
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
27
28from sas.sasgui.guiframe.dataFitting import Data1D
29from sas.sasgui.guiframe.dataFitting import Data2D
30
31
32def get_app_dir():
33    """
34        The application directory is the one where the default custom_config.py
35        file resides.
36
37        :returns: app_path - the path to the applicatin directory
38    """
39    # First, try the directory of the executable we are running
40    app_path = sys.path[0]
41    if os.path.isfile(app_path):
42        app_path = os.path.dirname(app_path)
43    if os.path.isfile(os.path.join(app_path, "custom_config.py")):
44        app_path = os.path.abspath(app_path)
45        logging.info("Using application path: %s", app_path)
46        return app_path
47
48    # Next, try the current working directory
49    if os.path.isfile(os.path.join(os.getcwd(), "custom_config.py")):
50        logging.info("Using application path: %s", os.getcwd())
51        return os.path.abspath(os.getcwd())
52
53    # Finally, try the directory of the sasview module
54    # TODO: gui_manager will have to know about sasview until we
55    # clean all these module variables and put them into a config class
56    # that can be passed by sasview.py.
57    logging.info(sys.executable)
58    logging.info(str(sys.argv))
59    from sas import sasview as sasview
60    app_path = os.path.dirname(sasview.__file__)
61    logging.info("Using application path: %s", app_path)
62    return app_path
63
64def get_user_directory():
65    """
66        Returns the user's home directory
67    """
68    userdir = os.path.join(os.path.expanduser("~"), ".sasview")
69    if not os.path.isdir(userdir):
70        os.makedirs(userdir)
71    return userdir
72
73def _find_local_config(confg_file, path):
74    """
75        Find configuration file for the current application
76    """
77    config_module = None
78    fObj = None
79    try:
80        fObj, path_config, descr = imp.find_module(confg_file, [path])
81        config_module = imp.load_module(confg_file, fObj, path_config, descr)
82    except ImportError:
83        logging.error("Error loading %s/%s: %s" % (path, confg_file, sys.exc_value))
84    finally:
85        if fObj is not None:
86            fObj.close()
87    logging.info("GuiManager loaded %s/%s" % (path, confg_file))
88    return config_module
89
90# Get APP folder
91PATH_APP = get_app_dir()
92DATAPATH = PATH_APP
93
94# GUI always starts from the App folder
95#os.chdir(PATH_APP)
96# Read in the local config, which can either be with the main
97# application or in the installation directory
98config = _find_local_config('local_config', PATH_APP)
99if config is None:
100    config = _find_local_config('local_config', os.getcwd())
101    if config is None:
102        # Didn't find local config, load the default
103        import sas.sasgui.guiframe.config as config
104        logging.info("using default local_config")
105    else:
106        logging.info("found local_config in %s", os.getcwd())
107else:
108    logging.info("found local_config in %s", PATH_APP)
109
110
111from sas.sasgui.guiframe.customdir  import SetupCustom
112c_conf_dir = SetupCustom().setup_dir(PATH_APP)
113custom_config = _find_local_config('custom_config', c_conf_dir)
114if custom_config is None:
115    custom_config = _find_local_config('custom_config', os.getcwd())
116    if custom_config is None:
117        msgConfig = "Custom_config file was not imported"
118        logging.info(msgConfig)
119    else:
120        logging.info("using custom_config in %s", os.getcwd())
121else:
122    logging.info("using custom_config from %s", c_conf_dir)
123
124#read some constants from config
125APPLICATION_STATE_EXTENSION = config.APPLICATION_STATE_EXTENSION
126APPLICATION_NAME = config.__appname__
127SPLASH_SCREEN_PATH = config.SPLASH_SCREEN_PATH
128WELCOME_PANEL_ON = config.WELCOME_PANEL_ON
129SPLASH_SCREEN_WIDTH = config.SPLASH_SCREEN_WIDTH
130SPLASH_SCREEN_HEIGHT = config.SPLASH_SCREEN_HEIGHT
131SS_MAX_DISPLAY_TIME = config.SS_MAX_DISPLAY_TIME
132if not WELCOME_PANEL_ON:
133    WELCOME_PANEL_SHOW = False
134else:
135    WELCOME_PANEL_SHOW = True
136try:
137    DATALOADER_SHOW = custom_config.DATALOADER_SHOW
138    TOOLBAR_SHOW = custom_config.TOOLBAR_SHOW
139    FIXED_PANEL = custom_config.FIXED_PANEL
140    if WELCOME_PANEL_ON:
141        WELCOME_PANEL_SHOW = custom_config.WELCOME_PANEL_SHOW
142    PLOPANEL_WIDTH = custom_config.PLOPANEL_WIDTH
143    DATAPANEL_WIDTH = custom_config.DATAPANEL_WIDTH
144    GUIFRAME_WIDTH = custom_config.GUIFRAME_WIDTH
145    GUIFRAME_HEIGHT = custom_config.GUIFRAME_HEIGHT
146    CONTROL_WIDTH = custom_config.CONTROL_WIDTH
147    CONTROL_HEIGHT = custom_config.CONTROL_HEIGHT
148    DEFAULT_PERSPECTIVE = custom_config.DEFAULT_PERSPECTIVE
149    CLEANUP_PLOT = custom_config.CLEANUP_PLOT
150    # custom open_path
151    open_folder = custom_config.DEFAULT_OPEN_FOLDER
152    if open_folder != None and os.path.isdir(open_folder):
153        DEFAULT_OPEN_FOLDER = os.path.abspath(open_folder)
154    else:
155        DEFAULT_OPEN_FOLDER = PATH_APP
156except AttributeError:
157    DATALOADER_SHOW = True
158    TOOLBAR_SHOW = True
159    FIXED_PANEL = True
160    WELCOME_PANEL_SHOW = False
161    PLOPANEL_WIDTH = config.PLOPANEL_WIDTH
162    DATAPANEL_WIDTH = config.DATAPANEL_WIDTH
163    GUIFRAME_WIDTH = config.GUIFRAME_WIDTH
164    GUIFRAME_HEIGHT = config.GUIFRAME_HEIGHT
165    CONTROL_WIDTH = -1
166    CONTROL_HEIGHT = -1
167    DEFAULT_PERSPECTIVE = None
168    CLEANUP_PLOT = False
169    DEFAULT_OPEN_FOLDER = PATH_APP
170
171DEFAULT_STYLE = config.DEFAULT_STYLE
172
173PLUGIN_STATE_EXTENSIONS = config.PLUGIN_STATE_EXTENSIONS
174OPEN_SAVE_MENU = config.OPEN_SAVE_PROJECT_MENU
175VIEW_MENU = config.VIEW_MENU
176EDIT_MENU = config.EDIT_MENU
177extension_list = []
178if APPLICATION_STATE_EXTENSION is not None:
179    extension_list.append(APPLICATION_STATE_EXTENSION)
180EXTENSIONS = PLUGIN_STATE_EXTENSIONS + extension_list
181try:
182    PLUGINS_WLIST = '|'.join(config.PLUGINS_WLIST)
183except AttributeError:
184    PLUGINS_WLIST = ''
185APPLICATION_WLIST = config.APPLICATION_WLIST
186IS_WIN = True
187IS_LINUX = False
188CLOSE_SHOW = True
189TIME_FACTOR = 2
190NOT_SO_GRAPH_LIST = ["BoxSum"]
191
192class Communicate(QtCore.QObject):
193    """
194    Utility class for tracking of the Qt signals
195    """
196    # File got successfully read
197    fileReadSignal = QtCore.pyqtSignal(list)
198
199    # Open File returns "list" of paths
200    fileDataReceivedSignal = QtCore.pyqtSignal(dict)
201
202    # Update Main window status bar with "str"
203    # Old "StatusEvent"
204    statusBarUpdateSignal = QtCore.pyqtSignal(str)
205
206    # Send data to the current perspective
207    updatePerspectiveWithDataSignal = QtCore.pyqtSignal(list)
208
209    # New data in current perspective
210    updateModelFromPerspectiveSignal = QtCore.pyqtSignal(QtGui.QStandardItem)
211
212    # New plot requested from the GUI manager
213    # Old "NewPlotEvent"
214    plotRequestedSignal = QtCore.pyqtSignal(str)
215
216    # Progress bar update value
217    progressBarUpdateSignal = QtCore.pyqtSignal(int)
218
219    # Workspace charts added/removed
220    activeGraphsSignal = QtCore.pyqtSignal(list)
221
222
223def updateModelItem(item, update_data, name=""):
224    """
225    Adds a checkboxed row named "name" to QStandardItem
226    Adds QVariant 'update_data' to that row.
227    """
228    assert isinstance(item, QtGui.QStandardItem)
229    assert isinstance(update_data, QtCore.QVariant)
230
231    checkbox_item = QtGui.QStandardItem(True)
232    checkbox_item.setCheckable(True)
233    checkbox_item.setCheckState(QtCore.Qt.Checked)
234    checkbox_item.setText(name)
235
236    # Add "Info" item
237    py_update_data = update_data.toPyObject()
238    if isinstance(py_update_data, (Data1D or Data2D)):
239        # If Data1/2D added - extract Info from it
240        info_item = infoFromData(py_update_data)
241    else:
242        # otherwise just add a naked item
243        info_item = QtGui.QStandardItem("Info")
244
245    # Add the actual Data1D/Data2D object
246    object_item = QtGui.QStandardItem()
247    object_item.setData(update_data)
248
249    # Set the data object as the first child
250    checkbox_item.setChild(0, object_item)
251
252    # Set info_item as the second child
253    checkbox_item.setChild(1, info_item)
254
255    # Append the new row to the main item
256    item.appendRow(checkbox_item)
257
258def plotsFromCheckedItems(model_item):
259    """
260    Returns the list of plots for items in the model which are checked
261    """
262    assert isinstance(model_item, QtGui.QStandardItemModel)
263
264    plot_data = []
265    # Iterate over model looking for items with checkboxes
266    for index in range(model_item.rowCount()):
267        item = model_item.item(index)
268        if item.isCheckable() and item.checkState() == QtCore.Qt.Checked:
269            # TODO: assure item type is correct (either data1/2D or Plotter)
270            plot_data.append(item.child(0).data().toPyObject())
271        # Going 1 level deeper only
272        for index_2 in range(item.rowCount()):
273            item_2 = item.child(index_2)
274            if item_2 and item_2.isCheckable() and item_2.checkState() == QtCore.Qt.Checked:
275                # TODO: assure item type is correct (either data1/2D or Plotter)
276                plot_data.append(item_2.child(0).data().toPyObject())
277
278    return plot_data
279
280def infoFromData(data):
281    """
282    Given Data1D/Data2D object, extract relevant Info elements
283    and add them to a model item
284    """
285    assert isinstance(data, (Data1D, Data2D))
286
287    info_item = QtGui.QStandardItem("Info")
288
289    title_item = QtGui.QStandardItem("Title: " + data.title)
290    info_item.appendRow(title_item)
291    run_item = QtGui.QStandardItem("Run: " + str(data.run))
292    info_item.appendRow(run_item)
293    type_item = QtGui.QStandardItem("Type: " + str(data.__class__.__name__))
294    info_item.appendRow(type_item)
295
296    if data.path:
297        path_item = QtGui.QStandardItem("Path: " + data.path)
298        info_item.appendRow(path_item)
299
300    if data.instrument:
301        instr_item = QtGui.QStandardItem("Instrument: " + data.instrument)
302        info_item.appendRow(instr_item)
303
304    process_item = QtGui.QStandardItem("Process")
305    if isinstance(data.process, list) and data.process:
306        for process in data.process:
307            process_date = process.date
308            process_date_item = QtGui.QStandardItem("Date: " + process_date)
309            process_item.appendRow(process_date_item)
310
311            process_descr = process.description
312            process_descr_item = QtGui.QStandardItem("Description: " + process_descr)
313            process_item.appendRow(process_descr_item)
314
315            process_name = process.name
316            process_name_item = QtGui.QStandardItem("Name: " + process_name)
317            process_item.appendRow(process_name_item)
318
319    info_item.appendRow(process_item)
320
321    return info_item
322
323def openLink(url):
324    """
325    Open a URL in an external browser.
326    Check the URL first, though.
327    """
328    parsed_url = urlparse.urlparse(url)
329    if parsed_url.scheme:
330        webbrowser.open(url)
331    else:
332        msg = "Attempt at opening an invalid URL"
333        raise AttributeError, msg
334
335def retrieveData1d(data):
336    """
337    Retrieve 1D data from file and construct its text
338    representation
339    """
340    try:
341        xmin = min(data.x)
342        ymin = min(data.y)
343    except:
344        msg = "Unable to find min/max of \n data named %s" % \
345                    data.filename
346        logging.error(msg)
347        raise ValueError, msg
348
349    text = data.__str__()
350    text += 'Data Min Max:\n'
351    text += 'X_min = %s:  X_max = %s\n' % (xmin, max(data.x))
352    text += 'Y_min = %s:  Y_max = %s\n' % (ymin, max(data.y))
353    if data.dy != None:
354        text += 'dY_min = %s:  dY_max = %s\n' % (min(data.dy), max(data.dy))
355    text += '\nData Points:\n'
356    x_st = "X"
357    for index in range(len(data.x)):
358        if data.dy != None and len(data.dy) > index:
359            dy_val = data.dy[index]
360        else:
361            dy_val = 0.0
362        if data.dx != None and len(data.dx) > index:
363            dx_val = data.dx[index]
364        else:
365            dx_val = 0.0
366        if data.dxl != None and len(data.dxl) > index:
367            if index == 0:
368                x_st = "Xl"
369            dx_val = data.dxl[index]
370        elif data.dxw != None and len(data.dxw) > index:
371            if index == 0:
372                x_st = "Xw"
373            dx_val = data.dxw[index]
374
375        if index == 0:
376            text += "<index> \t<X> \t<Y> \t<dY> \t<d%s>\n" % x_st
377        text += "%s \t%s \t%s \t%s \t%s\n" % (index,
378                                                data.x[index],
379                                                data.y[index],
380                                                dy_val,
381                                                dx_val)
382    return text
383
384def retrieveData2d(data):
385    """
386    Retrieve 1D data from file and construct its text
387    representation
388    """
389    text = data.__str__()
390    text += 'Data Min Max:\n'
391    text += 'I_min = %s\n' % min(data.data)
392    text += 'I_max = %s\n\n' % max(data.data)
393    text += 'Data (First 2501) Points:\n'
394    text += 'Data columns include err(I).\n'
395    text += 'ASCII data starts here.\n'
396    text += "<index> \t<Qx> \t<Qy> \t<I> \t<dI> \t<dQparal> \t<dQperp>\n"
397    di_val = 0.0
398    dx_val = 0.0
399    dy_val = 0.0
400    len_data = len(data.qx_data)
401    for index in xrange(0, len_data):
402        x_val = data.qx_data[index]
403        y_val = data.qy_data[index]
404        i_val = data.data[index]
405        if data.err_data != None:
406            di_val = data.err_data[index]
407        if data.dqx_data != None:
408            dx_val = data.dqx_data[index]
409        if data.dqy_data != None:
410            dy_val = data.dqy_data[index]
411
412        text += "%s \t%s \t%s \t%s \t%s \t%s \t%s\n" % (index,
413                                                        x_val,
414                                                        y_val,
415                                                        i_val,
416                                                        di_val,
417                                                        dx_val,
418                                                        dy_val)
419        # Takes too long time for typical data2d: Break here
420        if index >= 2500:
421            text += ".............\n"
422            break
423
424    return text
Note: See TracBrowser for help on using the repository browser.