source: sasview/src/sas/qtgui/GuiUtils.py @ e540cd2

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

Status bar, progress bar, initial treeview context menu + minor cleanup

  • Property mode set to 100755
File size: 11.0 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
220def updateModelItem(item, update_data, name=""):
221    """
222    Adds a checkboxed row named "name" to QStandardItem
223    Adds QVariant 'update_data' to that row.
224    """
225    assert isinstance(item, QtGui.QStandardItem)
226    assert isinstance(update_data, QtCore.QVariant)
227
228    checkbox_item = QtGui.QStandardItem(True)
229    checkbox_item.setCheckable(True)
230    checkbox_item.setCheckState(QtCore.Qt.Checked)
231    checkbox_item.setText(name)
232
233    # Add "Info" item
234    py_update_data = update_data.toPyObject()
235    if isinstance(py_update_data, (Data1D or Data2D)):
236        # If Data1/2D added - extract Info from it
237        info_item = infoFromData(py_update_data)
238    else:
239        # otherwise just add a naked item
240        info_item = QtGui.QStandardItem("Info")
241
242    # Add the actual Data1D/Data2D object
243    object_item = QtGui.QStandardItem()
244    object_item.setData(update_data)
245
246    # Set the data object as the first child
247    checkbox_item.setChild(0, object_item)
248
249    # Set info_item as the second child
250    checkbox_item.setChild(1, info_item)
251
252    # Append the new row to the main item
253    item.appendRow(checkbox_item)
254
255def plotsFromCheckedItems(model_item):
256    """
257    Returns the list of plots for items in the model which are checked
258    """
259    assert isinstance(model_item, QtGui.QStandardItemModel)
260
261    plot_data = []
262    # Iterate over model looking for items with checkboxes
263    for index in range(model_item.rowCount()):
264        item = model_item.item(index)
265        if item.isCheckable() and item.checkState() == QtCore.Qt.Checked:
266            # TODO: assure item type is correct (either data1/2D or Plotter)
267            plot_data.append(item.child(0).data().toPyObject())
268        # Going 1 level deeper only
269        for index_2 in range(item.rowCount()):
270            item_2 = item.child(index_2)
271            if item_2 and item_2.isCheckable() and item_2.checkState() == QtCore.Qt.Checked:
272                # TODO: assure item type is correct (either data1/2D or Plotter)
273                plot_data.append(item_2.child(0).data().toPyObject())
274
275    return plot_data
276
277def infoFromData(data):
278    """
279    Given Data1D/Data2D object, extract relevant Info elements
280    and add them to a model item
281    """
282    assert isinstance(data, (Data1D, Data2D))
283
284    info_item = QtGui.QStandardItem("Info")
285
286    title_item = QtGui.QStandardItem("Title: " + data.title)
287    info_item.appendRow(title_item)
288    run_item = QtGui.QStandardItem("Run: " + str(data.run))
289    info_item.appendRow(run_item)
290    type_item = QtGui.QStandardItem("Type: " + str(data.__class__.__name__))
291    info_item.appendRow(type_item)
292
293    if data.path:
294        path_item = QtGui.QStandardItem("Path: " + data.path)
295        info_item.appendRow(path_item)
296
297    if data.instrument:
298        instr_item = QtGui.QStandardItem("Instrument: " + data.instrument)
299        info_item.appendRow(instr_item)
300
301    process_item = QtGui.QStandardItem("Process")
302    if isinstance(data.process, list) and data.process:
303        for process in data.process:
304            process_date = process.date
305            process_date_item = QtGui.QStandardItem("Date: " + process_date)
306            process_item.appendRow(process_date_item)
307
308            process_descr = process.description
309            process_descr_item = QtGui.QStandardItem("Description: " + process_descr)
310            process_item.appendRow(process_descr_item)
311
312            process_name = process.name
313            process_name_item = QtGui.QStandardItem("Name: " + process_name)
314            process_item.appendRow(process_name_item)
315
316    info_item.appendRow(process_item)
317
318    return info_item
319
320def openLink(url):
321    """
322    Open a URL in an external browser.
323    Check the URL first, though.
324    """
325    parsed_url = urlparse.urlparse(url)
326    if parsed_url.scheme:
327        webbrowser.open(url)
328    else:
329        msg = "Attempt at opening an invalid URL"
330        raise AttributeError, msg
Note: See TracBrowser for help on using the repository browser.