source: sasview/src/sas/qtgui/GuiUtils.py @ 39551a68

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

More context menu functionality + tests

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