source: sasview/src/sas/qtgui/GuiUtils.py @ 0ba0774

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 0ba0774 was 27313b7, checked in by Piotr Rozyczko <rozyczko@…>, 8 years ago

Added window title GUI for charts

  • Property mode set to 100644
File size: 19.1 KB
Line 
1"""
2Global 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 periodictable import formula as Formula
29
30from sas.sasgui.guiframe.dataFitting import Data1D
31from sas.sasgui.guiframe.dataFitting import Data2D
32from sas.sascalc.dataloader.loader import Loader
33
34
35def get_app_dir():
36    """
37        The application directory is the one where the default custom_config.py
38        file resides.
39
40        :returns: app_path - the path to the applicatin directory
41    """
42    # First, try the directory of the executable we are running
43    app_path = sys.path[0]
44    if os.path.isfile(app_path):
45        app_path = os.path.dirname(app_path)
46    if os.path.isfile(os.path.join(app_path, "custom_config.py")):
47        app_path = os.path.abspath(app_path)
48        #logging.info("Using application path: %s", app_path)
49        return app_path
50
51    # Next, try the current working directory
52    if os.path.isfile(os.path.join(os.getcwd(), "custom_config.py")):
53        #logging.info("Using application path: %s", os.getcwd())
54        return os.path.abspath(os.getcwd())
55
56    # Finally, try the directory of the sasview module
57    # TODO: gui_manager will have to know about sasview until we
58    # clean all these module variables and put them into a config class
59    # that can be passed by sasview.py.
60    #logging.info(sys.executable)
61    #logging.info(str(sys.argv))
62    from sas import sasview as sasview
63    app_path = os.path.dirname(sasview.__file__)
64    #logging.info("Using application path: %s", app_path)
65    return app_path
66
67def get_user_directory():
68    """
69        Returns the user's home directory
70    """
71    userdir = os.path.join(os.path.expanduser("~"), ".sasview")
72    if not os.path.isdir(userdir):
73        os.makedirs(userdir)
74    return userdir
75
76def _find_local_config(confg_file, path):
77    """
78        Find configuration file for the current application
79    """
80    config_module = None
81    fObj = None
82    try:
83        fObj, path_config, descr = imp.find_module(confg_file, [path])
84        config_module = imp.load_module(confg_file, fObj, path_config, descr)
85    except ImportError:
86        pass
87        #logging.error("Error loading %s/%s: %s" % (path, confg_file, sys.exc_value))
88    finally:
89        if fObj is not None:
90            fObj.close()
91    #logging.info("GuiManager loaded %s/%s" % (path, confg_file))
92    return config_module
93
94# Get APP folder
95PATH_APP = get_app_dir()
96DATAPATH = PATH_APP
97
98# GUI always starts from the App folder
99#os.chdir(PATH_APP)
100# Read in the local config, which can either be with the main
101# application or in the installation directory
102config = _find_local_config('local_config', PATH_APP)
103
104if config is None:
105    config = _find_local_config('local_config', os.getcwd())
106    if config is None:
107        # Didn't find local config, load the default
108        import sas.sasgui.guiframe.config as config
109        #logging.info("using default local_config")
110    else:
111        pass
112        #logging.info("found local_config in %s", os.getcwd())
113else:
114    pass
115    #logging.info("found local_config in %s", PATH_APP)
116
117
118from sas.sasgui.guiframe.customdir  import SetupCustom
119c_conf_dir = SetupCustom().setup_dir(PATH_APP)
120custom_config = _find_local_config('custom_config', c_conf_dir)
121if custom_config is None:
122    custom_config = _find_local_config('custom_config', os.getcwd())
123    if custom_config is None:
124        msgConfig = "Custom_config file was not imported"
125        #logging.info(msgConfig)
126    else:
127        pass
128        #logging.info("using custom_config in %s", os.getcwd())
129else:
130    pass
131    #logging.info("using custom_config from %s", c_conf_dir)
132
133#read some constants from config
134APPLICATION_STATE_EXTENSION = config.APPLICATION_STATE_EXTENSION
135APPLICATION_NAME = config.__appname__
136SPLASH_SCREEN_PATH = config.SPLASH_SCREEN_PATH
137WELCOME_PANEL_ON = config.WELCOME_PANEL_ON
138SPLASH_SCREEN_WIDTH = config.SPLASH_SCREEN_WIDTH
139SPLASH_SCREEN_HEIGHT = config.SPLASH_SCREEN_HEIGHT
140SS_MAX_DISPLAY_TIME = config.SS_MAX_DISPLAY_TIME
141if not WELCOME_PANEL_ON:
142    WELCOME_PANEL_SHOW = False
143else:
144    WELCOME_PANEL_SHOW = True
145try:
146    DATALOADER_SHOW = custom_config.DATALOADER_SHOW
147    TOOLBAR_SHOW = custom_config.TOOLBAR_SHOW
148    FIXED_PANEL = custom_config.FIXED_PANEL
149    if WELCOME_PANEL_ON:
150        WELCOME_PANEL_SHOW = custom_config.WELCOME_PANEL_SHOW
151    PLOPANEL_WIDTH = custom_config.PLOPANEL_WIDTH
152    DATAPANEL_WIDTH = custom_config.DATAPANEL_WIDTH
153    GUIFRAME_WIDTH = custom_config.GUIFRAME_WIDTH
154    GUIFRAME_HEIGHT = custom_config.GUIFRAME_HEIGHT
155    CONTROL_WIDTH = custom_config.CONTROL_WIDTH
156    CONTROL_HEIGHT = custom_config.CONTROL_HEIGHT
157    DEFAULT_PERSPECTIVE = custom_config.DEFAULT_PERSPECTIVE
158    CLEANUP_PLOT = custom_config.CLEANUP_PLOT
159    # custom open_path
160    open_folder = custom_config.DEFAULT_OPEN_FOLDER
161    if open_folder != None and os.path.isdir(open_folder):
162        DEFAULT_OPEN_FOLDER = os.path.abspath(open_folder)
163    else:
164        DEFAULT_OPEN_FOLDER = PATH_APP
165except AttributeError:
166    DATALOADER_SHOW = True
167    TOOLBAR_SHOW = True
168    FIXED_PANEL = True
169    WELCOME_PANEL_SHOW = False
170    PLOPANEL_WIDTH = config.PLOPANEL_WIDTH
171    DATAPANEL_WIDTH = config.DATAPANEL_WIDTH
172    GUIFRAME_WIDTH = config.GUIFRAME_WIDTH
173    GUIFRAME_HEIGHT = config.GUIFRAME_HEIGHT
174    CONTROL_WIDTH = -1
175    CONTROL_HEIGHT = -1
176    DEFAULT_PERSPECTIVE = None
177    CLEANUP_PLOT = False
178    DEFAULT_OPEN_FOLDER = PATH_APP
179
180DEFAULT_STYLE = config.DEFAULT_STYLE
181
182PLUGIN_STATE_EXTENSIONS = config.PLUGIN_STATE_EXTENSIONS
183OPEN_SAVE_MENU = config.OPEN_SAVE_PROJECT_MENU
184VIEW_MENU = config.VIEW_MENU
185EDIT_MENU = config.EDIT_MENU
186extension_list = []
187if APPLICATION_STATE_EXTENSION is not None:
188    extension_list.append(APPLICATION_STATE_EXTENSION)
189EXTENSIONS = PLUGIN_STATE_EXTENSIONS + extension_list
190try:
191    PLUGINS_WLIST = '|'.join(config.PLUGINS_WLIST)
192except AttributeError:
193    PLUGINS_WLIST = ''
194APPLICATION_WLIST = config.APPLICATION_WLIST
195IS_WIN = True
196IS_LINUX = False
197CLOSE_SHOW = True
198TIME_FACTOR = 2
199NOT_SO_GRAPH_LIST = ["BoxSum"]
200
201class Communicate(QtCore.QObject):
202    """
203    Utility class for tracking of the Qt signals
204    """
205    # File got successfully read
206    fileReadSignal = QtCore.pyqtSignal(list)
207
208    # Open File returns "list" of paths
209    fileDataReceivedSignal = QtCore.pyqtSignal(dict)
210
211    # Update Main window status bar with "str"
212    # Old "StatusEvent"
213    statusBarUpdateSignal = QtCore.pyqtSignal(str)
214
215    # Send data to the current perspective
216    updatePerspectiveWithDataSignal = QtCore.pyqtSignal(list)
217
218    # New data in current perspective
219    updateModelFromPerspectiveSignal = QtCore.pyqtSignal(QtGui.QStandardItem)
220
221    # New plot requested from the GUI manager
222    # Old "NewPlotEvent"
223    plotRequestedSignal = QtCore.pyqtSignal(str)
224
225    # Progress bar update value
226    progressBarUpdateSignal = QtCore.pyqtSignal(int)
227
228    # Workspace charts added/removed
229    activeGraphsSignal = QtCore.pyqtSignal(list)
230
231    # Current workspace chart's name changed
232    activeGraphName = QtCore.pyqtSignal(tuple)
233
234
235def updateModelItemWithPlot(item, update_data, name=""):
236    """
237    Adds a checkboxed row named "name" to QStandardItem
238    Adds QVariant 'update_data' to that row.
239    """
240    assert isinstance(item, QtGui.QStandardItem)
241    assert isinstance(update_data, QtCore.QVariant)
242
243    checkbox_item = QtGui.QStandardItem(True)
244    checkbox_item.setCheckable(True)
245    checkbox_item.setCheckState(QtCore.Qt.Checked)
246    checkbox_item.setText(name)
247
248    # Add "Info" item
249    py_update_data = update_data.toPyObject()
250    if isinstance(py_update_data, (Data1D or Data2D)):
251        # If Data1/2D added - extract Info from it
252        info_item = infoFromData(py_update_data)
253    else:
254        # otherwise just add a naked item
255        info_item = QtGui.QStandardItem("Info")
256
257    # Add the actual Data1D/Data2D object
258    object_item = QtGui.QStandardItem()
259    object_item.setData(update_data)
260
261    # Set the data object as the first child
262    checkbox_item.setChild(0, object_item)
263
264    # Set info_item as the second child
265    checkbox_item.setChild(1, info_item)
266
267    # Append the new row to the main item
268    item.appendRow(checkbox_item)
269
270def updateModelItem(item, update_data, name=""):
271    """
272    Adds a simple named child to QStandardItem
273    """
274    assert isinstance(item, QtGui.QStandardItem)
275    assert isinstance(update_data, list)
276
277    # Add the actual Data1D/Data2D object
278    object_item = QtGui.QStandardItem()
279    object_item.setText(name)
280    object_item.setData(QtCore.QVariant(update_data))
281
282    # Append the new row to the main item
283    item.appendRow(object_item)
284
285
286def plotsFromCheckedItems(model_item):
287    """
288    Returns the list of plots for items in the model which are checked
289    """
290    assert isinstance(model_item, QtGui.QStandardItemModel)
291
292    plot_data = []
293    # Iterate over model looking for items with checkboxes
294    for index in range(model_item.rowCount()):
295        item = model_item.item(index)
296        if item.isCheckable() and item.checkState() == QtCore.Qt.Checked:
297            # TODO: assure item type is correct (either data1/2D or Plotter)
298            plot_data.append(item.child(0).data().toPyObject())
299        # Going 1 level deeper only
300        for index_2 in range(item.rowCount()):
301            item_2 = item.child(index_2)
302            if item_2 and item_2.isCheckable() and item_2.checkState() == QtCore.Qt.Checked:
303                # TODO: assure item type is correct (either data1/2D or Plotter)
304                plot_data.append(item_2.child(0).data().toPyObject())
305
306    return plot_data
307
308def infoFromData(data):
309    """
310    Given Data1D/Data2D object, extract relevant Info elements
311    and add them to a model item
312    """
313    assert isinstance(data, (Data1D, Data2D))
314
315    info_item = QtGui.QStandardItem("Info")
316
317    title_item = QtGui.QStandardItem("Title: " + data.title)
318    info_item.appendRow(title_item)
319    run_item = QtGui.QStandardItem("Run: " + str(data.run))
320    info_item.appendRow(run_item)
321    type_item = QtGui.QStandardItem("Type: " + str(data.__class__.__name__))
322    info_item.appendRow(type_item)
323
324    if data.path:
325        path_item = QtGui.QStandardItem("Path: " + data.path)
326        info_item.appendRow(path_item)
327
328    if data.instrument:
329        instr_item = QtGui.QStandardItem("Instrument: " + data.instrument)
330        info_item.appendRow(instr_item)
331
332    process_item = QtGui.QStandardItem("Process")
333    if isinstance(data.process, list) and data.process:
334        for process in data.process:
335            process_date = process.date
336            process_date_item = QtGui.QStandardItem("Date: " + process_date)
337            process_item.appendRow(process_date_item)
338
339            process_descr = process.description
340            process_descr_item = QtGui.QStandardItem("Description: " + process_descr)
341            process_item.appendRow(process_descr_item)
342
343            process_name = process.name
344            process_name_item = QtGui.QStandardItem("Name: " + process_name)
345            process_item.appendRow(process_name_item)
346
347    info_item.appendRow(process_item)
348
349    return info_item
350
351def openLink(url):
352    """
353    Open a URL in an external browser.
354    Check the URL first, though.
355    """
356    parsed_url = urlparse.urlparse(url)
357    if parsed_url.scheme:
358        webbrowser.open(url)
359    else:
360        msg = "Attempt at opening an invalid URL"
361        raise AttributeError, msg
362
363def retrieveData1d(data):
364    """
365    Retrieve 1D data from file and construct its text
366    representation
367    """
368    if not isinstance(data, Data1D):
369        msg = "Incorrect type passed to retrieveData1d"
370        raise AttributeError, msg
371    try:
372        xmin = min(data.x)
373        ymin = min(data.y)
374    except:
375        msg = "Unable to find min/max of \n data named %s" % \
376                    data.filename
377        #logging.error(msg)
378        raise ValueError, msg
379
380    text = data.__str__()
381    text += 'Data Min Max:\n'
382    text += 'X_min = %s:  X_max = %s\n' % (xmin, max(data.x))
383    text += 'Y_min = %s:  Y_max = %s\n' % (ymin, max(data.y))
384    if data.dy != None:
385        text += 'dY_min = %s:  dY_max = %s\n' % (min(data.dy), max(data.dy))
386    text += '\nData Points:\n'
387    x_st = "X"
388    for index in range(len(data.x)):
389        if data.dy != None and len(data.dy) > index:
390            dy_val = data.dy[index]
391        else:
392            dy_val = 0.0
393        if data.dx != None and len(data.dx) > index:
394            dx_val = data.dx[index]
395        else:
396            dx_val = 0.0
397        if data.dxl != None and len(data.dxl) > index:
398            if index == 0:
399                x_st = "Xl"
400            dx_val = data.dxl[index]
401        elif data.dxw != None and len(data.dxw) > index:
402            if index == 0:
403                x_st = "Xw"
404            dx_val = data.dxw[index]
405
406        if index == 0:
407            text += "<index> \t<X> \t<Y> \t<dY> \t<d%s>\n" % x_st
408        text += "%s \t%s \t%s \t%s \t%s\n" % (index,
409                                                data.x[index],
410                                                data.y[index],
411                                                dy_val,
412                                                dx_val)
413    return text
414
415def retrieveData2d(data):
416    """
417    Retrieve 2D data from file and construct its text
418    representation
419    """
420    if not isinstance(data, Data2D):
421        msg = "Incorrect type passed to retrieveData2d"
422        raise AttributeError, msg
423
424    text = data.__str__()
425    text += 'Data Min Max:\n'
426    text += 'I_min = %s\n' % min(data.data)
427    text += 'I_max = %s\n\n' % max(data.data)
428    text += 'Data (First 2501) Points:\n'
429    text += 'Data columns include err(I).\n'
430    text += 'ASCII data starts here.\n'
431    text += "<index> \t<Qx> \t<Qy> \t<I> \t<dI> \t<dQparal> \t<dQperp>\n"
432    di_val = 0.0
433    dx_val = 0.0
434    dy_val = 0.0
435    len_data = len(data.qx_data)
436    for index in xrange(0, len_data):
437        x_val = data.qx_data[index]
438        y_val = data.qy_data[index]
439        i_val = data.data[index]
440        if data.err_data != None:
441            di_val = data.err_data[index]
442        if data.dqx_data != None:
443            dx_val = data.dqx_data[index]
444        if data.dqy_data != None:
445            dy_val = data.dqy_data[index]
446
447        text += "%s \t%s \t%s \t%s \t%s \t%s \t%s\n" % (index,
448                                                        x_val,
449                                                        y_val,
450                                                        i_val,
451                                                        di_val,
452                                                        dx_val,
453                                                        dy_val)
454        # Takes too long time for typical data2d: Break here
455        if index >= 2500:
456            text += ".............\n"
457            break
458
459    return text
460
461def onTXTSave(data, path):
462    """
463    Save file as formatted txt
464    """
465    with open(path,'w') as out:
466        has_errors = True
467        if data.dy == None or data.dy == []:
468            has_errors = False
469        # Sanity check
470        if has_errors:
471            try:
472                if len(data.y) != len(data.dy):
473                    has_errors = False
474            except:
475                has_errors = False
476        if has_errors:
477            if data.dx != None and data.dx != []:
478                out.write("<X>   <Y>   <dY>   <dX>\n")
479            else:
480                out.write("<X>   <Y>   <dY>\n")
481        else:
482            out.write("<X>   <Y>\n")
483
484        for i in range(len(data.x)):
485            if has_errors:
486                if data.dx != None and data.dx != []:
487                    if  data.dx[i] != None:
488                        out.write("%g  %g  %g  %g\n" % (data.x[i],
489                                                        data.y[i],
490                                                        data.dy[i],
491                                                        data.dx[i]))
492                    else:
493                        out.write("%g  %g  %g\n" % (data.x[i],
494                                                    data.y[i],
495                                                    data.dy[i]))
496                else:
497                    out.write("%g  %g  %g\n" % (data.x[i],
498                                                data.y[i],
499                                                data.dy[i]))
500            else:
501                out.write("%g  %g\n" % (data.x[i],
502                                        data.y[i]))
503
504def saveData1D(data):
505    """
506    Save 1D data points
507    """
508    default_name = os.path.basename(data.filename)
509    default_name, extension = os.path.splitext(default_name)
510    default_name += "_out" + extension
511
512    wildcard = "Text files (*.txt);;"\
513                "CanSAS 1D files(*.xml)"
514    kwargs = {
515        'caption'   : 'Save As',
516        'directory' : default_name,
517        'filter'    : wildcard,
518        'parent'    : None,
519    }
520    # Query user for filename.
521    filename = QtGui.QFileDialog.getSaveFileName(**kwargs)
522
523    # User cancelled.
524    if not filename:
525        return
526
527    filename = str(filename)
528
529    #Instantiate a loader
530    loader = Loader()
531    if os.path.splitext(filename)[1].lower() == ".txt":
532        onTXTSave(data, filename)
533    if os.path.splitext(filename)[1].lower() == ".xml":
534        loader.save(filename, data, ".xml")
535
536def saveData2D(data):
537    """
538    Save data2d dialog
539    """
540    default_name = os.path.basename(data.filename)
541    default_name, _ = os.path.splitext(default_name)
542    ext_format = ".dat"
543    default_name += "_out" + ext_format
544
545    wildcard = "IGOR/DAT 2D file in Q_map (*.dat)"
546    kwargs = {
547        'caption'   : 'Save As',
548        'directory' : default_name,
549        'filter'    : wildcard,
550        'parent'    : None,
551    }
552    # Query user for filename.
553    filename = QtGui.QFileDialog.getSaveFileName(**kwargs)
554
555    # User cancelled.
556    if not filename:
557        return
558    filename = str(filename)
559    #Instantiate a loader
560    loader = Loader()
561
562    if os.path.splitext(filename)[1].lower() == ext_format:
563        loader.save(filename, data, ext_format)
564
565class FormulaValidator(QtGui.QValidator):
566    def __init__(self, parent=None):
567        super(FormulaValidator, self).__init__(parent)
568 
569    def validate(self, input, pos):
570        try:
571            Formula(str(input))
572            self._setStyleSheet("")
573            return QtGui.QValidator.Acceptable, pos
574
575        except Exception as e:
576            self._setStyleSheet("background-color:pink;")
577            return QtGui.QValidator.Intermediate, pos
578
579    def _setStyleSheet(self, value):
580        try:
581            if self.parent():
582                self.parent().setStyleSheet(value)
583        except:
584            pass
585
586def dataFromItem(item):
587    """
588    Retrieve Data1D/2D component from QStandardItem.
589    The assumption - data stored in SasView standard, in child 0
590    """
591    return item.child(0).data().toPyObject()
Note: See TracBrowser for help on using the repository browser.